Laravel雄辩的关系2个不同的列

我正在尝试在2个模型之间建立关系。

我有2个模型:User&Synergy

表用户有一个名为employee_id的列,employee_id必须与res_id列上的表Synergy匹配

在模型用户中我添加了:

public function Synergy(){
    return $this->hasOne('App\Synergy');
}

模型协同作用:

class Synergy extends Model
{
    protected $connection = 'sqlsrv1';
    protected $table = 'humres';
    protected $primaryKey = 'employee_id';

    public function user(){
        return $this->belongsTo('App\User');
    }
}

使用此模型,查询为:

select top 1 * from [humres] where [humres].[user_id] = 1 and [humres].[user_id] is not null

但我想要

select top 1 * from [humres] where [humres].[res_id] = <COLUMN EMPLOYEE_ID> and [humres].[res_id] is not null
jhfuuu 回答:Laravel雄辩的关系2个不同的列

在这种情况下,您需要显式说明关系的列名。试试这个:

class Synergy extends Model
{
    protected $connection = 'sqlsrv1';
    protected $table = 'humres';
    protected $primaryKey = 'employee_id';

    public function user(){
        return $this->belongsTo('App\User','res_id');
    }
}

在用户模型中;

public function synergy(){
    return $this->hasOne('App\Synergy','employee_id');
}

将小写 s 用于synergy关系。

有关更多详细信息,请参见the documentation

本文链接:https://www.f2er.com/3159890.html

大家都在问