我目前正在尝试从“organizations”表中获取一些信息,然后需要从“organization_stocks”表中获取有关该组织的一些值,但我只想要最新的匹配项,并且只有那个匹配项(所以 1 个匹配项每个组织)
这是我当前的代码,但如您所见,它返回属于同一组织的多行。
$data = DB::table('organization_stocks')
->rightJoin('organizations', 'organizations.id', '=', 'organization_stocks.organization_id')
->select('organizations.id', 'organizations.name', 'organization_stocks.value', 'organization_stocks.change', 'organization_stocks.state')
->where('active', '=', '1')
->orderBy('organization_stocks.timestamp', 'desc')
->take(5)
->get();
谢谢。
最佳答案
如果您只想要最新的比赛,您只需使用 ->first();
而不是 ->get()
因为您已经订购了它们,所以您应该美好的。我假设 timestamp
是您的列等同于 created_at
?
您可以在此处查看更多信息:http://laravel.com/docs/4.2/eloquent
文档中给出的例子:$comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();
编辑:您也可以在不需要所有连接的情况下通过简单地正确设置模型关系来实现您想要的,如果您需要进一步阅读这篇文章可能会有所帮助:http://culttt.com/2013/06/10/laravel-4-eloquent-model-relationships/
关于php - Laravel Join 只选择一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812245/