【问题标题】:Getting unique models in nested Many To Many Relationship在嵌套的多对多关系中获取独特的模型
【发布时间】:2020-04-19 00:48:55
【问题描述】:

您好 StackOverflow 用户!

我正在为一项非常简单的任务而苦苦挣扎,如果你们中的任何一位能帮助我,我将非常感激。 我有 3 个具有嵌套多对多关系的模型。

我的第一个模型是 Wave,它与 Employee 有 M2M 关系:

Wave.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Wave extends Model
{

    public function employees()
    {
        return $this->belongsToMany('App\Employee');
    }

Employee 有一个多对多 Wave 和另一个多对多 Expertise

Employee.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{

    public function waves()
    {
        return $this->belongsToMany('App\Wave');
    }

    public function expertises()
    {
        return $this->belongsToMany('App\Expertise');
    }


最后是我的 Expertise 模型与 Employee 的多对多:

Expertise.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Expertise extends Model
{

    public function employees()
    {
        return $this->belongsToMany('App\Employee');
    }

我想在这里实现的是在 Wave 上创建一个自定义属性,以获取 员工 分配给此的所有不同的专业知识 波拥有。

它看起来是不同专长的一维集合。

这似乎不是很复杂,但我尝试了很多东西,但无法让它工作。

我尝试的最后一件事是使用 withwithPivotIn 查询专业模型,但没有成功:

Wave.php


    public function getExpertisesAttribute()
    {
        $employees = $this->employees;
        $expertises = Expertise::with('employees', function($q) use($employees) {
            $q->wherePivotIn('employee_id', $employees->pluck('id')->toArray());
        });
        return $expertises;
    }

运行此查询时出现错误:

PHP Warning: mb_strpos() expects parameter 1 to be string, object given in /Users/Kaz/lab/MyProject/vendor/laravel/framework/src/Illuminate/Support/Str.php on line 107

仅供参考,我在 PHP 7.2 上使用 Laravel 5.8

非常感谢您阅读本文,我希望您能给我一些帮助,因为我感觉有点卡住了,但这似乎是一件容易的事!

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    你可能正在寻找 Laravel 的 whereHas() 方法。此方法将强制仅返回与波对象中包含的employees 具有employee 关系的Expertises

    试试这个。根据需要进行调整,但这应该会让您到达您想去的地方:

    $employees = $this->employees;
    $employees_ids = $employees->pluck('id')->toArray();
    $expertises = Expertise::with('employees')->whereHas('employees', function ($query) use ($employees_ids) {
        $query->whereIn('employees.id', $employees_ids);
    })->get();
    
    dd($expertises);
    

    【讨论】:

    • 一切正常,非常感谢!我以前已经用过 whereHas 但完全忘记了,再次感谢你:)!
    猜你喜欢
    • 2022-11-04
    • 1970-01-01
    • 2015-03-13
    • 2019-01-24
    • 2021-04-24
    • 2014-12-27
    • 2014-01-22
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多