with
方法来避免 1+N
查询,可是 with
会将目标关联的全部字段所有查询出来,对于有强迫症的PHPer来讲,固然是不容许发生的。方便简洁,可是不能针对不一样的需求去关联不一样的字段,一旦在模型关联中写死,全部的关联的字段都是同样的函数
在user模型里,写关联函数,一对多。此模型放在APP\Models下,默认放在App下post
1 public function hasPost(){ 2 return $this->hasMany('App\Models\post','外键','主键')->select('id','content','title'); 3 }
这种方法比较自由,是在各自的逻辑控制器里实现,比较自由this
1 public function test(User $user) 2 { 3 $return_datas = $user->with(['hasPost'=>function($query){ 4 $query-select('主键','外键','content','title'); 5 }) ->get(); 6 }
在基础模型里spa
1 class BaseModel extends \Eloquent{ 2 public function scopeWithOnly($query, $relation, Array $columns) 3 { 4 return $query->with([$relation => function ($query) use ($columns){ 5 $query->select(array_merge(['id'], $columns)); 6 }]); 7 } 8 }
在咱们普通的 Model 类都继承基类:code
1 class User extends BaseModel{ 2 public function hasPost() 3 { 4 return $this->hasMany('App\Models\post') 5 } 6 }
再接着逻辑实现本身想要的blog
1 1 public function test(User $user) 2 2 { 3 3 $return_datas = $user->with(['hasPost',['字段1','字段2',.....]) ->get(); 4 6 }