我是一个来自CakePHP的开发人员,用Laravel做我的第一个项目。在CakePHP中,当我定义模型及其关系时,有一个选项可以在关系上设置连接策略:strategy
(join
或select
)。默认情况下,它使用join
,当我加载相关模型时,它将通过添加JOIN
语句在单个查询中这样做。您可以选择使用select
来生成单独的查询。
例如,当我在Laravel中使用急切加载时:
$user = App\User::with(['articles'])->first();
这实际上会生成两个查询,一个用于获取用户的记录,另一个用于获取相关的文章。这与我在我的select
模型中指定了CakePHP策略一样。但是,我希望使用join
策略,这样我就可以按照相关表的列进行排序或过滤。我还没找到办法。像这样的东西在拉拉/雄辩中存在吗?
发布于 2020-01-06 12:30:38
使用Laravel,它非常简单地使用Joins获取记录。假设左联接,这是获取记录的示例代码:(您还可以使用任何一个连接-最适合您的需要)
//assuming **title** and **description** as amongst the article fields
// and that you've passed the user's id as **$user_id**
//I've also assumed the articles table has a user id field **user_id** which has the corresponding user's id.
$user = App\User::leftJoin('articles','users.id','articles.user_id')
->where('users.id',$user_id)
->select('users.*','artcles.title as title','articles.description as description')
->get();
https://stackoverflow.com/questions/59611910
复制相似问题