Rodolfo Rodolfo - 6 months ago 26
PHP Question

Translate raw complex SQL query into Eloquent

Can anyone help me translate this into Eloquent?

select * from resources
left join links
on links.resource_id = resources.id
and (links.ud_id IS NULL OR links.ud_id = '7')
where resources.user_id = '1'
and resources.subject_id = '4'


Thank you in advance

Answer

This should do the trick:

DB::table('resources')
  ->leftJoin('links', function($join) {
    $join->on('links.resource_id', '=', 'resources.id');
    $join->where(function($query) {
      $query->whereNull('links.ud_id');
      $query->orWhere('links.ud_id', 7);
    });
  })
  ->where('user_id', 1)
  ->where('subject_id', 4)
  ->get();
Comments