[英]Laravel eloquent multiple table join with filter
我的系统中有3个表。
学生可以写许多文章,而一篇文章仅属于一个学生。 文章只能有一个类别。
控制者
public function all_articles_by_student_by_category(Request $request){
$students_id = $request->students_id;
$categories_id = $request->categories_id;
$article_list = Students::find($students_id)->articles->all();
//This return Something like, Select All Articles Written by Damith
}
模型
class Students extends Model
{
protected $fillable = ['id','first_name', 'last_name', 'age', 'created_at', 'updated_at'];
public function articles()
{
return $this->hasMany('App\Articles');
}
}
我试图得到什么
诸如“选择由Damith撰写的所有文章作为技术类别”(类别名称应在此处)
到目前为止我能做的
像这样,使用$article_list = Students::find($students_id)->articles->all();
来选择由Damith撰写的所有文章$article_list = Students::find($students_id)->articles->all();
(您可以从控制器中找到此代码)
我想要你的
我如何修改$article_list = Students::find($students_id)->articles->all();
得到类似“由Damith撰写的所有文章作为技术类别”的信息。 ( 结果中必须存在类别名称,并且该类别名称位于类别表上,对于此条件,您可以使用商品表中的category_id )
这样的事情应该起作用:
$technologyArticles = Articles::where('student_id', '=', $students_id)->where('category_id', '=', $categories_id)->get();
首先,使用到目前为止的操作,在获取模型上某个关系的记录时不需要->all()
方法,这将返回链接到该学生的所有文章:
Students::find($students_id)->articles
通过文章模型
您可以执行以下操作:
Article::where('student_id', $students_id)
->where('category_id', $category_id)->get();
这将实现您追求的结果。
通过学生模型
如果要通过Students
Model
,可以使用with
方法约束关系。
$student = Students::with(['articles' => function($query) use ($category_id) {
$query->where('category_id', $category_id);
}])->find($student_id);
$filteredArticles = $student->articles
有用的链接
Eager Loading
: https ://laravel.com/docs/5.5/eloquent-relationships#eager-loading 当访问Eloquent关系作为属性时,关系数据是“延迟加载”的。 这意味着直到您首次访问该属性,关系数据才被实际加载。 但是,Eloquent可以在查询父模型时“急于加载”关系。
Constraining Eager Loads
: https ://laravel.com/docs/5.5/eloquent-relationships#constraining-eager-loads 有时,您可能希望加载一个关系,但同时为加载加载查询指定其他查询约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.