【问题标题】:Laravel Datables Search Include Pivot Table ResultsLaravel 数据表搜索包括数据透视表结果
【发布时间】:2018-06-04 07:44:47
【问题描述】:

在我解释我要做什么之前,可能值得先提一下以下信息。

我有 3 张桌子: - 用户 - 职位空缺 - user_vacancy

空缺可以有一个所有者,该所有者由空缺表上的外键 user_id 指示。

许多其他用户可以是团队成员,可以使用数据透视表 user_vacancy 将其分配到相同的空缺

我试图通过 Vacancy 模型在数据表中列出一个用户的所有空缺,无论他们是空缺的所有者还是团队成员,我的代码如下所示:

VacancyController.php:

public function get_user_vacancies() {
    $user = User::find(auth()->id());

    $vacancies = Vacancy::with(['team_members' => function($q) use ($user) {
          $q->where('user_id', $user->id);
    }])->where('user_id', $user->id);

    $dataTables = Datatables::of($vacancies);

    $dataTables->make(true);
}

Vacancy.php:

public function team_members()
{
    return $this->belongsToMany('App\Models\Access\User\User')->withPivot('id', 'created_at', 'updated_at');
}

用户.php:

public function team_vacancies()
{
    return $this->belongsToMany('App\Vacancy')->withPivot('id', 'created_at', 'updated_at');
}

我明白为了将“团队成员空缺”与“所有者空缺”一起加入“团队成员空缺”,我显然做错了,但我不太确定如何正确处理。

我希望有人可以帮助我或为我指明正确的方向。

【问题讨论】:

    标签: php datatables eloquent laravel-5.2 pivot-table


    【解决方案1】:

    您应该在模型中为 team_members 方法添加关联表的名称,如下所示:

    public function team_vacancies()
    {
        return $this->belongsToMany('App\Vacancy', 'user_vacancy')->withPivot('id', 'created_at', 'updated_at');
    }
    

    如果在User.php 中通过vacanciesteamsVacancy.php 中重命名您的方法会很好

    【讨论】:

    • 您好 Thamer,感谢您的回复,我会记住最后几个提示。我也试过 - return $this->belongsToMany('App\Models\Access\User\User', 'user_vacancy', 'vacancy_id', 'user_id')->withPivot('id', 'created_at', 'updated_at');由于某种原因,它不会返回用户是团队成员的空缺,而只会返回用户是空缺所有者的空缺。例如,如果有 40 个职位空缺的用户是所有者,而有 6 个职位空缺的用户是团队成员,则它只会检索 40 个结果而不是 46 个结果。
    猜你喜欢
    • 2021-08-06
    • 2018-04-10
    • 2021-01-22
    • 2021-10-20
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多