Laravel 中的 With() 方法是什么?

Cho*_*oy 1 php laravel eloquent

我参考了一些在线参考资料以了解如何处理 laravel 中的 With 方法,但仍然不明白。 Laravel with():这个方法有什么作用?

这里有一些我不明白的代码,我可以知道 a、b、c、d、e、f 指的是什么吗?

 $example = Test::with('a', 'b', 'c',
            'd', 'e', 'f');
Run Code Online (Sandbox Code Playgroud)

Dil*_*ara 5

给你一个直接的例子。如果您有用户表并且该用户表与多个表相关,对吗?它也属于多个表。

在这里,我拿四张桌子。

城市

  1. ID
  2. 姓名

用户

  1. ID
  2. 姓名
  3. city_id

用户资料

  1. ID
  2. 用户身份
  3. 地址
  4. 电话

用户文档

  1. ID
  2. 用户身份
  3. 文件名
  4. 类型

用户belongsTo一城市,

用户has one资料

用户has many文档。

现在,在 User 模型中,您可以定义如下关系。

用户名

//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();
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您想访问控制器中的所有数据,则可以使用with()

控制器

App\User::with('city','profile','documents')->get();
Run Code Online (Sandbox Code Playgroud)

你会得到对象中的所有数据


用户

ID

姓名

  • {城市数据}

  • {轮廓}

  • {文件}


此外,您还可以获取多个模型嵌套关系,就像城市属于州一样,如果您想获取带有城市的州数据,

User::with('city.state','profile','documents')->get(): 
//define state relationship in city model you'll get state data with the city as well.
Run Code Online (Sandbox Code Playgroud)

您还可以添加条件 with()

User::with(['document'=>function ($q){
    $q->where('type','pdf');
}]);
Run Code Online (Sandbox Code Playgroud)