从多个表中获取数据 Laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35904942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Data from Multiple Tables Laravel
提问by Gaurav Mehta
I am trying to build a coupon site in Laravel. Each merchant has their own deals/coupons. I have been able to print deals/coupons for a merchant on their specific pages.
我正在尝试在 Laravel 中建立一个优惠券网站。每个商家都有自己的优惠/优惠券。我已经能够在他们的特定页面上为商家打印交易/优惠券。
Here's my query
这是我的查询
$deals = DB::table('deals')
-> join ('merchants', 'deals.merchant_id', '=', 'merchants.merchant_id')
-> where ('merchant_url_text', $merchant_url_text)
-> get();
So far so good.
到现在为止还挺好。
Now this is where it starts getting complex.
现在这就是它开始变得复杂的地方。
Each deal has 2 more pieces associated with it. Click counts and Votes associated with deals.
每笔交易都有 2 件与之相关联。与交易相关的点击次数和投票数。
The click counts are in a table called clicks which records each click on the website. The click record will have a click id associated it. So I would need to get a count of clicks each deal gets.
点击计数位于名为 clicks 的表格中,该表格记录网站上的每次点击。点击记录将有一个与其相关联的点击 ID。所以我需要计算每笔交易获得的点击次数。
The second piece is votes. The votes around a deal are stored in a deal_votes
table. The deal_votes
table has deal_id
, vote
(1
or 0
)
第二部分是投票。围绕交易的投票存储在deal_votes
表中。该deal_votes
表有deal_id
, vote
(1
或0
)
How do I combine click counts and deal votes to return in the same query so that I can display the info in my view?
如何组合点击计数和交易投票以在同一查询中返回,以便我可以在我的视图中显示信息?
回答by Jeff
Do you have models and relationships set up for merchants, deals, coupons, and clicks? This is trivial if you use Eloquent models with relationships, for which the docs are here: https://laravel.com/docs/5.2/eloquent-relationships
您是否为商家、交易、优惠券和点击设置了模型和关系?如果您使用带有关系的 Eloquent 模型,这是微不足道的,文档在这里:https: //laravel.com/docs/5.2/eloquent-relationships
This would look like:
这看起来像:
$merchant = Merchant::where('merchant_url_text', $merchant_url_text)
->with('deals','deals.votes','deals.clicks')
->first();
The with()
function adds all of the nested information, ie query join
s, into a single query.
该with()
函数将所有嵌套信息(即查询join
)添加到单个查询中。
In your view:
在您看来:
@foreach($merchant->deals as $deal)
Deal: {{$deal->name}}
Clicks: {{count($deal->clicks)}}
Votes: {{$deal->votes->sum('vote')}}
@endforeach