I have created a model in Laravel.
class deals extends Model
{
//
protected $table = 'tbl_deal';
}
Now I want to use this model to retrieve data in my Controller. However, the data extracted from this model also needs to be constrained by a column in another table. Below is the basic schema
tbl_deal
- deal_id
- merchant_id
- deal_text
tbl_merchant
- merchant_id
- merchant_url_text
My current Controller has the following code to extract all deals from deals model.
$deals = deals::all();
I want to constraint the deals by merchant_url_text. Since that is in merchant table, I would need to join it with the existing deal model.
Any help on how I can do that in my controller and if this is the right way to solve this kind of problem.
Thanks.
Best Answer
Add to your
deals
modelthe following function (called relationship):
and now you will be able to get all deals with merchant using
For example to display the first one use:
However to use this you need to create also
Merchant
model and using this method nojoin
will be used.In case you want to use simple join instead of relationship in this case, you can use:
And now to display 1st merchant text you can use:
I strongly recommend to read Laravel documentation to fully understand basic Laravel concepts before writing any code (for example by convention model name should be
Deal
instead ofdeals
and table name should bedeals
instead oftbl_deal
, similar for primary key - it should be simpleid
instead ofdeal_id
).