Patrick
Patrick

Reputation: 101

How to add "where" clause in relationship eloquent way?

I have 3 tables :

And the relation of the table are :

And now i need to access by this way :

$response = User::select(['user_id'])->first();
$response->transactionHeader->transactionDetail->where('trans_detail_id', '=', '1');

The code above show the correct data BUT cannot filtered by ->where('trans_detail_id', '=', '1');. trans_detail_id is inside transactionDetail table. NO error but my problem is why the data not filtered by trans_detail_id='1' ?

Please fix my code and explain why?

Thank you

Upvotes: 1

Views: 1391

Answers (3)

Masud Miah
Masud Miah

Reputation: 256

you can try this way :

$response = User::select(['user_id'])->first();
$response->transactionHeader()->transactionDetail()->where('trans_detail_id', '=', '1');

and this way will also work :

$response = User::select(['user_id'])->with(['transactionHeader.transactionDetail' => function($query) {
        $query->where('trans_detail_id', 1);
}])->first();

but now you want to use a variable data instead of 1 for 'trans_detail_id'

$value = $request->value_to_filter_data;

$response = User::select(['user_id'])->with(['transactionHeader.transactionDetail' => function($query) use ($value) {
            $query->where('trans_detail_id',$value);
    }])->first();

Upvotes: 0

John Flores
John Flores

Reputation: 1

Hope it helps !

$response->transactionHeader->transactionDetail->where('trans_detail_id', '1');

Upvotes: -1

Alex Harris
Alex Harris

Reputation: 6402

Have you tried eager loading the relations with a query on the nested relation?

$response = User::select(['user_id'])->with(['transactionHeader.transactionDetail' => function($query) {
        $query->where('trans_detail_id', 1);
}])->first();

Upvotes: 2

Related Questions