如何在定义模型关系时在inter table not relation table上添加条件

问题描述 投票:0回答:3

我有一个名为company_team的关系表它与companyuser的关系,并且在is_ceo表中有一个字段company_team来标记公司团队成员是首席执行官的天气。以下是我的模型定义

class CompanyTeam extends Pivot
{
    /**
     * return all company team member with out ceo
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function team_member()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * return only ceo's info
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function company_ceo()
    {
        $this->where('is_ceo', 1); // it dosen't work, but it is effect l want
        return $this->belongsTo(User::class, 'user_id');
    }
}

我使用addGlobalScope搜索答案,但它不适合我,因为当我同时使用team_membercompany_ceo关系时,它会在两者上添加条件

laravel eloquent php-7 laravel-5.7
3个回答
0
投票

定义关系时无法添加条件。您必须在执行查询时添加条件。

CompanyTeam::with(['company_ceo' => function ($q) use() { $q->where('is_ceo', 1); }]) ->get();


0
投票
public function company_ceo()
{
    return $this->belongsTo(User::class, 'user_id')->where('is_ceo', 1);
}

我希望这有帮助。有一个美好的一天,快乐的编码...... :)


0
投票

在用户模型中,您可以定义范围

public function scopeCompanyCeo($query){
return $query->where('is_ceo',1);
}

那么你可以在你的控制器中使用

$user = User::find(1)->companyCeo()->get();
© www.soinside.com 2019 - 2024. All rights reserved.