Laravel雄辩的多表加入过滤器

问题描述:

我的系统中有三个表。Laravel雄辩的多表加入过滤器

  1. 学生
  2. 文章
  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();才能获得类似的内容,请选择所有文章作者:Damith for Technology Category。 (类别名称必须为那里的结果,它是类别表,并在那里condtion你可以使用CATEGORY_ID这是我在文章表

+0

答案很简单,请查看Laravel有关如何使用口才的文档。如果你能够做一个普通的SQL查询,这意味着你可以用雄辩的方式做到这一点。只要学习语法。 – Desh901

首先与你迄今所做的不需要->all()方法获取记录在模型上的关系时,这将返回所有链接到该学生的文章:

Students::find($students_id)->articles 

经过文章型号
你可以这样做:

Article::where('student_id', $students_id) 
    ->where('category_id', $category_id)->get(); 

这将acheive结果你是经过。


经过学生型号

如果你想通过StudentsModel可以使用with法约束的关系。

$student = Students::with(['articles' => function($query) use ($category_id) { 
    $query->where('category_id', $category_id); 
}])->find($student_id); 

$filteredArticles = $student->articles 

有效链接

当访问作为属性口才的关系,所述关系数据是 “延迟加载” 。这意味着关系数据在第一次访问该属性之前并未实际加载。但是,Eloquent可以在查询父模型时“加载”关系。

有时你不妨渴望负载的关系,同时也为预先加载查询指定其他查询约束。

+0

感谢您的详细解答。我正在阅读这篇文章和'Article :: where('student_id',$ students_id) - > where('category_id',$ category_id) - > get();'工作正常。 。我认为这返回只是'选择*从文章where student_id = 2和categories_id = 3' ..........现在我的问题是Laravel如何知道文章表和类别表应该只加入'where('category_id' ,'=',$ categories_id)'line? –

+0

@IamtheMostStupidPerson如果您还有其他问题,请点击[提问](http://stackoverflow.com/questions/ask)按钮。你需要完全解释你现在需要的帮助。请参阅Laravel文档:https://laravel.com/docs/5.5/eloquent-relationships – Purgatory

+0

@IamtheMostStupidPerson如果您想要为学生提供数据,则可能需要尝试“通过学生模型”方法。 – Purgatory

像这样的东西应该工作:

$technologyArticles = Articles::where('student_id', '=', $students_id)->where('category_id', '=', $categories_id)->get(); 
+0

谢谢。这工作。我认为这个返回只是'select * from文章where student_id = 2和categories_id = 3' ..........现在我的问题是Laravel如何知道文章表和类别表应该只是在'where'('category_id' ,'=',$ categories_id)'line? –

+0

@IamtheMostStupidPerson如果还有其他问题,请点击[Ask Question](问问题)(http://stackoverflow.com/questions/ask)按钮。你需要完全解释你现在需要的帮助。请参阅Laravel文档:https://laravel.com/docs/5.5/eloquent-relationships – Purgatory