jeudi 24 mars 2016

Find result with hasmany relationship in laravel

I am just starts a project in laravel and this is new environment for me. I am familiar with PHP and also models relationship. But the laravel structure is little bit complex for starting. So the problem is I have a question and Course table, A single question may have more then one course so i created one more table which hold course id and question id.

Question Model

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Question extends Model{

    protected $primaryKey = "id";

    public function courses(){
        return $this->hasMany('App\Models\CourseQuestion');
    }
}

Course model

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Course extends Model {
    protected $primaryKey = "id";

    public function questions(){
        return $this->hasOne('App\Models\CourseQuestion');
    }
} 

And last courseQuestion model

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class CourseQuestion extends Model {
    protected $primaryKey = "id";

    public function questions(){
        return $this->hasOne('App\Models\Question');
    }

    public function courses(){
        return $this->hasMany('App\Models\Course');
    }
}

And my controller where i getting result -

class IndexController extends BaseController {

    public function index(){
        $user = Question::with('user','courses','branches')->find(100);
        echo "<pre>";
        print_r($user); die;
    }
}

So the courses return only id of course and questions which store in third table but i want the course name respective id. Please help Thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire