Laravel-按不同关系过滤记录

Laravel-按不同关系过滤记录,laravel,eloquent,laravel-query-builder,Laravel,Eloquent,Laravel Query Builder,现在我有以下模型结构 Country->State->City->Student 而学生模型包括名和姓 所以,我想通过给学生的名字来过滤国家。比如,如果我给出John,那么我想要一份学生名字是John的国家名单 我试过这样的东西 我在Country模型中添加了一个名为Student()的方法,并从该方法返回Student实例。但现在我坚持要找出如何过滤国家 谢谢你的期待 我最近遇到了一个类似的问题,我自己提出了以下解决方案。也许有更简单的方法,但我想这会让你暂时离开 首先,如您所述,我们使用Fi

现在我有以下模型结构

Country->State->City->Student

学生
模型包括

所以,我想通过给学生的名字来过滤国家。比如,如果我给出
John
,那么我想要一份学生名字是
John
的国家名单

我试过这样的东西

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


谢谢你的期待

我最近遇到了一个类似的问题,我自己提出了以下解决方案。也许有更简单的方法,但我想这会让你暂时离开

首先,如您所述,我们使用
First\u 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();

在学生模型中,创建以下内容:

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

你可以这样访问

如果已正确设置模型和关系,则需要使用in with函数调用它们

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

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

我做的和你说的一样,但它抛出了一个
BadMethodCallException
异常,
Method-Illumb\Database\Query\Builder::students不存在
。你能给我看看你在国家/地区模型上创建的
students()
方法吗?(参考您在此处所说的:“我在Country model中添加了一个名为Students()的方法,并从该方法返回学生实例。”)可能的重复:您的学生表具有Country_id或city_id?@DsRaj Only city_idOkay,您需要名称以John开头的学生的国家/地区列表,比如:name:John Dark Country:UK,姓名:John Due国家:美国right@DsRaj是的,对