【转:laravel5】laravel 中with关联查询限定查询字段

1、laravel 中with关联查询限定查询字段

2、转载:https://www.cnblogs.com/sgm4231/archive/2004/01/13/9639620.html

学习了下laravel5.6框架,果然很优雅,比如ActiveJieSuan model中作如下关联:(laravel模型关联关系可以查看https://laravelacademy.org/post/8867.html)

   只需在ActiveJieSuan 模型中设定

protected $with = ['user','actice'];
那么查询ActiveJieSuan就能自动关联上users,actice_contents表。

如果要限定关联查询的字段,可以如下写法:
ActiveJieSuan::with(['user' => function ($query) {$query->select('id','name');},
   'active'=> function ($query) {$query->select('id','name','start');}])
->paginate()->toArray();
如此限定后查询的结果就只是users表中的id和name字段,active_contents表中的id,name,start字段和active_jiesuan表全部字段了.
更简洁的写法:
ActiveJieSuan::with(['user:id,name','active:id,name,start']) ->paginate()->toArray();
原文地址:https://www.cnblogs.com/xuzhengzong/p/14306203.html