简体   繁体   中英

Conditional Laravel Eloquent relation

I have a table note with id, note, type_id, about_id . Here the type_id refers to the different type like task(601), discussion (602), images (603), etc. And about_id refers to the id of respected type table.

$note = Notes::with('tasks')->with('discussion')->with('images')->get();

This returned notes with all the ->with() table value. How can I get the values of related table according to the type_id . I tried

$note=Notes::where('deleted_at', null);
$note=$note->WhereHas('tasks', function($q) use($note)
{
    $note->Where('type_id',601);
})->get();

Is it possible to get only related tables value using eloquent.

Using Use($note) unnecessary , Remove this and use $q instead

   $note = Notes::where('deleted_at', null)
   ->whereHas('tasks', function($q){ 
        $q->where('type_id',601); 
   })->get();

Also include ->with('tasks') if you want get all related tasks

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