0

im trying to join two tables post and comment using ORM relations,

$posts = Post::with('comments')->get(); 

how can i use condition on comments when using with to join tables?

i can use whereHas like

$posts = Post::whereHas('comments', function ($query) {
    if(isset($_GET['title']))
    $query->where('title', $_GET['title']);
})->get();

but when i use whereHas i wouldn't get the post without any comment in the result

basically i want to use left join with condition on the right table

sam
  • 127
  • 1
  • 9

2 Answers2

2

You can pass a closure to with() method like this:

$posts = Post::with(['comments' => function($q) {
    $q->where('column', '=', 'value'); // Put conditions here
}])->get();

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
0

You need use Closures:

$title = $_GET['title'];
$posts = Post::whereHas('comments', function ($query) use ($title) {
    if(!empty($title)) {
        $query->where('title', $_GET['title']);
    }
})->get();

Reference:

In PHP 5.3.0, what is the function "use" identifier?

Community
  • 1
  • 1
Andre Rodrigues
  • 253
  • 3
  • 6