[英]Laravel Eloquent ORM - Nested with statements
So I'm creating an API for a web application I'm creating and I'm trying to keep it within the Eloquent ORM. 所以我正在创建一个我正在创建的Web应用程序的API,并且我正在尝试将其保留在Eloquent ORM中。 There is a parent-child relationship that I have going on:
我有一个亲子关系:
User -> Site Logs -> Sites 用户 - >站点日志 - >站点
Site class code: 网站类代码:
class Site extends Model {
public function log() {
return $this->hasMany('App\SiteLog', 'site_id', 'id');
}
}
SiteLog class code: SiteLog类代码:
class SiteLog extends Model
{
public function site()
{
return $this->belongsTo('App\Site', 'site_id', 'id');
}
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
}
When I instantiate the SiteLog class using: 当我使用以下方法实例化SiteLog类时:
$sites = Site::with('log')->get();
When I make the GET request with jQuery, I get all of the sites and inside of them I have an array of objects with all of the data for the sites respective logs. 当我使用jQuery发出GET请求时,我获得了所有站点,并且在其中我有一个对象数组,其中包含站点各自日志的所有数据。 Which is exactly what I wanted.
这正是我想要的。 However, I wanted to take it a step further and get the user that the log is associated with.
但是,我想更进一步,让用户与日志相关联。
Sort of like how this would work: 有点像这将如何工作:
SiteLog::with('user')->get();
But all in one statement as if it was one big join query. 但是在一个声明中,好像它是一个大的连接查询。 However, I'm not sure if the Eloquent ORM covers a test case like that.
但是,我不确定Eloquent ORM是否涵盖了这样的测试用例。
Has anybody ever accomplished something like this? 有没有人做过这样的事情? I can get this done with some pretty hacky practices or just writing a raw SQL query, but I am just wondering if there was a more eloquent way of doing this.
我可以通过一些非常糟糕的实践或只是编写原始SQL查询来完成这项工作,但我只是想知道是否有更有说服力的方法来做到这一点。
Eloquent allows you to do that easily :) Eloquent允许你轻松地做到这一点:)
https://laravel.com/docs/5.2/eloquent-relationships#eager-loading https://laravel.com/docs/5.2/eloquent-relationships#eager-loading
If you also need the user related with each log you just have to eager load it like this 如果您还需要与每个日志相关的用户,您只需要像这样急切加载它
$sites = Site::with('log.user')->get();
Something like: 就像是:
Site::with('log.user')->get();
Laravel 5.2 Docs - Eloquent - Relationships - Eager Loading - Nested Eager Loading Laravel 5.2 Docs - Eloquent - Relationships - Eager Loading - 嵌套Eager Loading
You would end up with a structure something like: 你最终得到的结构如下:
Site
log: [
SiteLog
User
SiteLog
User
...
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.