Laravel Eloquent关联:2个不同的列

3

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

我有两个模型:用户和协同作用。

用户表具有名为employee_id的列,employee_id必须匹配到Synergy表上的res_id列。

在用户模型中,我添加了:

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
1个回答

4
在这种情况下,您需要明确指定关系所使用的列名。请尝试以下内容:
class Synergy extends Model
{
    protected $connection = 'sqlsrv1';
    protected $table = 'humres';
    protected $primaryKey = 'employee_id';

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

在 User 模型中:
public function synergy(){
    return $this->hasOne('App\Synergy', 'employee_id');
}

使用小写字母 s 表示 synergy 关系。

请参阅 文档 以获取更多详细信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接