【问题标题】:Laravel Eloquent wherePivot method returns column 'pivot' not foundLaravel Eloquent wherePivot 方法返回未找到列“pivot”
【发布时间】:2019-07-25 14:04:47
【问题描述】:

我在现有的 Laravel 安装中设置了用户和代理之间的多对多数据库关系。

在前端,我使用下拉过滤器将agency_id 发送到应该通过此agency_id 变量过滤/返回所有用户的服务器。

在我的模型中: 用户.php

/**
 * The agencies that belong to the user.
 */
public function agencies()
{
    return $this->belongsToMany('App\Agency');
}

Agency.php

/**
 * The users that belong to the agency.
 */
public function users()
{
    return $this->belongsToMany('App\User');
}

当我查询数据库时,我检查代理参数是否存在于标题中

->when($request->agency, function ($q) use ($request, $schema) {
    // Determine whether agency_id foreign key exists or if it's a pivot relationship
    if(Schema::hasColumn($schema, 'agency_id'))
    {
        return $this
               ->repository
               ->whereAgency($q, \Hashids::decode($request->agency)[0]);
    }
    else
    {
        return $this
                ->repository
                ->whereAgencyPivot($q, \Hashids::decode($request->agency)[0]);
    }
})

在存储库中,我执行以下操作:

public function whereAgencyPivot($q, string $agency)
{
    return $q->wherePivot('agency_id', $agency);
}

这会返回以下错误:

找不到列:1054 'where 子句'中的未知列'pivot'

我也试过了:

public function whereAgencyPivot($q, string $agency)
{
    return $q->agencies()->where('agency_user.agency_id', $agency);
}

返回:

调用未定义的method Illuminate\Database\Eloquent\Builder::agencies()

我有什么遗漏的吗?

【问题讨论】:

    标签: php mysql laravel laravel-5 eloquent


    【解决方案1】:

    因此,您希望针对预先选择的agency 获取所有users,该users 在多对多关系中与users 链接。如果我理解错了,请纠正我。


    建立多对多关系

    Agency::with('users')->where('id', 1)->get(); // id is injected dynamically.
    


    有条件地加载关系

    if(some condition) {
     $agency->load('users'); // It'll fetch all users against the given agency.
    }
    


    仅获取用户信息

    $data = Agency::with('users')->where('id', 1)->first();
    $data->users; // gives you only users collection
    

    【讨论】:

    • 所有这些方法都查询代理模型。我需要查询用户模型。这可能吗?
    • 这些方法从给定机构的用户模型中获取数据。所以结果看起来像: {agency_id: 1, agency_name: 'abc', users: [{user_id: 1, user_name: 'abc'}, {second users}]} 。我想这就是你要照顾的
    【解决方案2】:

    答案是:

    return $q->whereHas('agencies', function($query) use ($agency) {
               $query->where('id', $agency);
           });
    

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 2017-05-10
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多