问题
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.
回答1:
Add to your deals
model
the following function (called relationship):
public function merchant()
{
return $this->belongsTo(Merchant::class, merchant_id);
}
and now you will be able to get all deals with merchant using
$deals = deals::with('merchant')->get();
For example to display the first one use:
$deal = $deals->first();
echo $deal->merchant->merchant_url_text;
However to use this you need to create also Merchant
model and using this method no join
will be used.
In case you want to use simple join instead of relationship in this case, you can use:
$deals = deals::selectRaw('tbl_deal.*, tbl_merchant.merchant_url_text')
->leftJoin('tbl_merchant','tbl_deal.merchant_id','=','table_merchant.merchant_id')->get();
And now to display 1st merchant text you can use:
$deal = $deals->first();
echo $deal->merchant_url_text;
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 of deals
and table name should be deals
instead of tbl_deal
, similar for primary key - it should be simple id
instead of deal_id
).
来源:https://stackoverflow.com/questions/34423319/joining-model-with-table-laravel-5-2