我使用Eloquent在laravel中跟随两个模型:
家长评估模型如下:
class Appraisal extends \Eloquent
{
protected $table = 'scope_appraisal';
protected $primaryKey = 'appraisal_id';
public function appraisalInfo()
{
return $this->hasOne('AppraisalInfo', 'appraisal_id', 'appraisal_id');
}
}
关系评估信息模型如下:
class AppraisalInfo extends \Eloquent
{
protected $table = 'scope_appraisal_info';
protected $primaryKey = 'appraisal_info_id';
public function appraisal()
{
return $this->belongsTo('V2_0\Appraisal', 'appraisal_id', 'appraisal_id');
}
public function scopeBorrowerName($query, $name)
{
return $query->where('appraisal_info_borrower', 'LIKE', '%' . trim($name) . '%');
}
}
我在控制器中使用“LeftJoin”进行查询,如下所示:
// QUERY USING LEFT JOIN
$queryObj = Appraisal::leftJoin('scope_appraisal_info', function ($join)
{
$join->on('scope_appraisal.appraisal_id', '=', 'scope_appraisal_info.appraisal_id');
});
$queryObj = $queryObj->borrowerName('xyzname');
$result = $queryObj->get();
但是,它回复了我的错误如下:
调用未定义的方法Illuminate \ Database \ Query \ Builder :: borrowerName()
那么,如何使用上述查询从关系模型访问范围..?
如果有人知道,请告诉我....谢谢!
答案 0 :(得分:0)
不是一个聪明的方法,但你可以实现如下:
$queryObj = Appraisal::leftJoin('scope_appraisal_info', function ($join)
{
$join->on('scope_appraisal.appraisal_id', '=', 'scope_appraisal_info.appraisal_id');
$join = (new AppraisalInfo())->scopeBorrowerName($join, 'xyzname');
});
但是,除非你必须使用范围我建议使用"其中"在加入。
$name = 'xyzname';
$queryObj = Appraisal::leftJoin('scope_appraisal_info', function ($join) use ($name)
{
$join->on('scope_appraisal.appraisal_id', '=', 'scope_appraisal_info.appraisal_id')
->where('appraisal_info_borrower', 'LIKE', '%' . trim($name) . '%');
});
在Laravel 5.2上。