[英]what's the With() method in laravel?
I had refer some online references for understanding what to do with With method in laravel but still not understand.我参考了一些在线参考资料以了解如何处理 laravel 中的 With 方法,但仍然不明白。 Laravel with(): What this method does?
Laravel with():这个方法有什么作用?
Here are some codes which I'm not understand, may I know what the a,b,c,d,e,f refer to?这里有一些我不明白的代码,我可以知道 a、b、c、d、e、f 指的是什么吗?
$example = Test::with('a', 'b', 'c',
'd', 'e', 'f');
Let's give you a direct example.给你一个直接的例子。 If you've user table and that user table related to multiple tables right??
如果您有用户表并且该用户表与多个表相关,对吗? and it belongs to multiple tables as well.
它也属于多个表。
Here, I take Four tables.
在这里,我拿四张桌子。
city城市
User用户
user_profile用户资料
user_documents用户文档
User
belongsTo
one city,用户
belongsTo
一个城市,User
has one
profile用户
has one
个人资料User
has many
documents.用户
has many
文件。
Now, In the User model, you can define the relationship as below.现在,在 User 模型中,您可以定义如下关系。
User.php用户名
//User belongs To City
public function city(){
return $this->belongsTo('App\City','city_id','id')->withDefault();
}
//User hasone profile
public function profile(){
return $this->hasOne('App\Profile','user_id','id')->withDefault();
}
//User hasmany document
public function documents(){
return $this->hasMany('App\UserDocument','user_id','id')->withDefault();
}
Now if you want to access this all data in the controller then you can get it by using with()现在,如果您想访问控制器中的所有数据,则可以使用with()
Controller控制器
App\User::with('city','profile','documents')->get();
you'll get all data in object as你会得到对象中的所有数据
User用户
id ID
name姓名
{city data} {城市数据}
{profile} {轮廓}
{documents} {文件}
In addition, You can get multiple model nested relationship as well, Like city belongs to state and if you want to get state data with city then,此外,您还可以获取多个模型嵌套关系,就像城市属于州一样,如果您想获取带有城市的州数据,
User::with('city.state','profile','documents')->get():
//define state relationship in city model you'll get state data with the city as well.
You can also add condition in
with()
您还可以在
with()
添加条件
User::with(['document'=>function ($q){
$q->where('type','pdf');
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.