2

I am fairly new to Laravel.

I am attempting to extract data from my database using Laravel's Eloquent query builder, I can extract all data without a problem, however I want to add a constraint to the second table in the relationship which SHOULD result in no data returning at all if its not true.

However when I try this, I doesn't return the second tables data but still returns the initial tables data, causing havoc in my view.

This is what I have:

$accounts = Account::with(array('booking' => function($query)
{
     $query->where('status', '=', 'booked');
}))
->get();

I am making sure to setup the relationship in the model, however for some reason I get a response like this:

  ["attributes":protected]=>
  array(4) {
    ["booking_id"]=>
    int(1)
    ["account_paid"]=>
    int(1)
    ["created_at"]=>
    string(19) "2016-10-22 11:10:49"
    ["updated_at"]=>
    string(19) "2016-10-22 11:10:49"
  }
  ["original":protected]=>
  array(4) {
    ["booking_id"]=>
    int(1)
    ["account_paid"]=>
    int(1)
    ["created_at"]=>
    string(19) "2016-10-22 11:10:49"
    ["updated_at"]=>
    string(19) "2016-10-22 11:10:49"
  }
  ["relations":protected]=>
  array(1) {
    ["booking"]=>
    NULL
  }

With booking set to null, however what I want is for nothing to return at all if the condition is false.

2 Answers 2

2

This should work for you:

$accounts = Account::with('booking')
    ->whereHas(['booking' => function($q)
    {
        $q->where('status', 'booked');
    }])
    ->get();
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! exactly what I was looking for! thank you! :)
1
$accounts = Account::with(array('booking' => function($query)
     {
          $query->where('status', '=', 'booked');
      }))
     ->whereHas(array('booking' => function($query)
     {
          $query->where('status', '=', 'booked');
      }))
    ->get();

This is the alternative way.

1 Comment

This was almost perfect! I actually used it to figure out Alexey Mazenin's solution just before seeing his post :D Thanks for your help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.