简体   繁体   中英

Eloquent laravel --> Eager Loading

i have the next structure:

model call content

public function credits(){

    return $this->belongsToMany('App\models\Credit');
}

model call Credit

 public function content()
{
    return $this->belongsToMany('App\models\Content');
}

What i am triying to do is extract all the credits of one content, but selecting only the columns that i want, with the below code:

$credits2=$this->content::with(array('credits'=>function($query){
        $query->select('id','department','job');
 }))->where('id',$id_content)->get();

The problem that i have is that when i execute all the code the result is:

[]

but if i do a normal query in mysql i can figure out that for the movie exists credits.

I have extracted this code, from other forums, and stackoverflow post.

There is another easy way to specify columns without using closure:

 $credits2 = $this->content::with('credits:credits.id,department,job')
                  ->find($id_content->id);

The problem was that $id_content was a result from a previous query, so if i put $id_content didn't work, for that i have to access to the column.

And the solution is:

$credits2=$this->content::with(array('credits'=>function($query){
    $query->select('id','department','job');
 }))->where('id',$id_content)->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM