There are theree tables in my system.
- Students
- Articles
- categories
Student can write many articles and a article is belong to just one student. And A Article can have only one category.
Controller
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
}
Model
class Students extends Model
{
protected $fillable = ['id','first_name', 'last_name', 'age', 'created_at', 'updated_at'];
public function articles()
{
return $this->hasMany('App\Articles');
}
}
What I am try to get
Something like, Select All Articles Written by Damith for Technology Category (Category Name should be there)
What I able to do so far
Something like, Select All Articles Written by Damith using $article_list = Students::find($students_id)->articles->all();
(You can find this code from controller)
What I want from you
How do I modify $article_list = Students::find($students_id)->articles->all();
to get, something like, Select All Articles Written by Damith for Technology Category. (Category name must be there in result and it is on category table, and for where condtion you can use the category_id which is i the article table )
First off with what you have done so far the
->all()
method is not needed when getting the records for a relation on a model, this would return all of the articles linked to that student:Go through Articles Model
You could do something like:
Which would acheive the result you are after.
Go through Students Model
If you want to go through
Students
Model
you can constrain the relation using thewith
method.Useful Links
Eager Loading
: https://laravel.com/docs/5.5/eloquent-relationships#eager-loadingConstraining Eager Loads
: https://laravel.com/docs/5.5/eloquent-relationships#constraining-eager-loads