laravel中的连表查询,如果用使用DB类,有的时候会很不方便。
官方文档中给出一种 Eloquent:关联 ,但是个人比较喜欢下面这种方式。
<?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $table = 'user'; //关联表 protected $primaryKey = 'user_id'; //主键 public $timestamps = true; //是否被自动维护时间戳 protected $guarded = []; //不可被赋值的属性 public function getUserInfo($user_id){ $where['user.auser_id'] = $user_id; $user_info = $this->leftJoin('phone','user.auser_id','=','phone.auser_id')->where($where)->get(); return $list ? $list->toArray() : false; } } //用这种方式写 很方便也很好用 dd((new User())->getUserInfo(1)); //甚至你可以在controller中组装好where条件直接传递进来 <?php namespace App\Http\Model; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $table = 'user'; //关联表 protected $primaryKey = 'user_id'; //主键 public $timestamps = true; //是否被自动维护时间戳 protected $guarded = []; //不可被赋值的属性 public function getUserList($where){ $user_info = $this->leftJoin('phone','user.auser_id','=','phone.auser_id')->where($where)->get(); return $list ? $list->toArray() : false; } } //controller中组装好where条件 $where['user.gender'] = 0; $where['user.status'] = 1; dd((new User())->getUserList($where));