user1785684 user1785684 - 1 month ago 15
PHP Question

Laravel Relationships (With)

I am fairly new to Laravel, so forgive me if this question seems stupid, I've been looking for a while now and have been unable to find anything helpful, so here I am asking.

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.

I hope I'm making sense :( Thank you for anyone who might be able to help me in advance.

Regards,

Answer

This should work for you:

$accounts = Account::with('booking')
    ->whereHas(['booking' => function($q)
    {
        $q->where('status', 'booked');
    }])
    ->get();
Comments