首页 > 解决方案 > 过滤结果有很多关系

问题描述

我正在努力过滤一些结果。我有一个名为“Process”的表,另一个名为“Actors”。流程有很多演员。这是模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Process extends Model
{
    public function actors()
    {
        return $this->hasMany(Actor::class)->orderBy('actor');
    }
}

所以我有一个观点,我展示了所有的过程和他们的演员。问题是,我想创建一个过滤选项,在这里我会检查Auth::user()->username是否与 Actor->actor 相同。

我尝试了一些类似的东西:

public function index()
    {
        $processes = Process::all();

        $processes ->actors()->where('actor', 'Test')->get();

        return view('process.process', compact('processes '));

    }

(在我为测试目的与测试进行比较的地方,如果我确实让它工作,我会将其更改为Auth::user()->username显然)

这显示以下错误:

BadMethodCallException 方法 Illuminate\Database\Eloquent\Collection::actors 不存在。

I've tried some variations(running a foreach in the controller for example, but either I did it wrong or thats not the way to do it...) but to no avail. Any help is greatly apreciated!

标签: phpmysqllaravel

解决方案


I assume that you want to grab all processes of the current authenticated user if yes this is what you need.

public function index()
{
    $processes = Process::whereHas('actors',function($query){
                     $query->where('id',Auth::user()->id);
                  });

    return view('process.process', compact('processes '));

}

推荐阅读