Ad

Laravel: A Model That Belongs To Two Other Models

In laravel, is there a way to get the list of objects that belong to two models?

For example,

Model transactions: belongs to users belongs to category

Model user: has many transactions

Model category: has many transactions

Assuming these relationships are correctly defined, what kind of query would you make in, say the controller, to access the set of transactions that belongs to user x and category y?

Ad

Answer

Assuming that your Transaction table has the foreign keys for user_id and category_id, you could do:

$transactions = Transaction::where('user_id', '=', 'x')
                          ->where('category_id ', '=', 'y')
                          ->get();
Ad
source: stackoverflow.com
Ad