【问题标题】:Laravel - Filter records by distinct relationLaravel - 按不同关系过滤记录
【发布时间】:2018-12-14 16:47:42
【问题描述】:

现在我有以下模型结构,

Country -> State -> City -> Student

而Student 模型包括first_name 和last_name。

所以,我希望通过提供学生的名字来过滤国家/地区。就像如果我给 John 那么我想要一个国家的列表,这些国家的学生的名字是 John。

我正在尝试这样的事情,

我在Country 模型中添加了一个名为Students() 的方法,并从该方法返回Student 实例。但现在我坚持要找出如何过滤国家/地区。

感谢期待。

【问题讨论】:

  • 你的学生表有 country_id 或 city_id?
  • @DsRaj Only city_id
  • 好的,你想要名字以 John 开头的学生的国家/地区列表让我们说:姓名:John Dark Country:UK,姓名:John Due Country:US right
  • @DsRaj 是的,对

标签: laravel eloquent laravel-query-builder


【解决方案1】:

我最近遇到了一个类似的问题,我自己提出了以下解决方案。可能有更简单的方法,但我想这会让你暂时继续前进。

首先,我们使用first_name == John 查询所有用户,如您所述,我们将查询限制为仅输出 ID。

$users = User::where('first_name', 'John')->get()->pluck('id');

然后我们将其与国家模型中Students() 的结果进行交叉比较。由于我不知道您要查询什么才能获得所需的国家/地区,因此我将仅以荷兰为例-这就是我来自的地方。

$users = Country::where('name', 'the Netherlands')->students()->whereIn('id', $users)->get();

为此,您必须确保在模型的 Students() 函数中,get() 被省略。

最终“结果”:

$users = User::where('first_name', 'John')->get()->pluck('id');
$users = Country::where('name', 'the Netherlands')->students()->whereIn('id', $users)->get();

【讨论】:

  • 我按照你说的做了同样的事情,但是它抛出了一个 BadMethodCallException 异常,Method Illuminate\Database\Query\Builder::students does not exist。
  • 您能告诉我您在国家模型上创建的Students() 方法吗? (参考您在这里所说的:“我在 Country 模型中添加了一个名为 Students() 的方法,并从该方法返回 Student 实例。”)
【解决方案2】:

在学生模型中创建:

public function city()
    {
        return $this->belongsTo(City::class,'city_id', 'id');
    }

在城市模型中创建这个:

public function state()
    {
        return $this->belongsTo(State::class,'state_id', 'id');
    }

终于进入状态模型:

public function country()
    {
        return $this->belongsTo(Country::class,'country_id', 'id');
    }

例如,如果你在控制器中做了类似的事情:

$students = Student::where('name', 'John')->get();

在视图中:

@foreach($students as $student)
$student->city->state->country->country_name;
@endforeach

你可以这样访问。

【讨论】:

    【解决方案3】:

    如果你已经正确设置了模型和关系,那么你需要使用函数调用它们

    $students = Student::where('name','John')->with('city.state.country')->get();
    

    循环通过$students

    @foreach($students as $student)
         {{ $student->city->state->country }}
    @endif
    

    【讨论】:

      猜你喜欢
      • 2016-10-15
      • 2021-07-22
      • 2021-12-15
      • 2014-01-15
      • 2017-02-28
      • 2020-01-25
      • 1970-01-01
      • 2020-12-17
      • 2021-06-12
      相关资源
      最近更新 更多