I have three table
id title body categories_id user_id
id user_name user_type
I want to show articles with their category name instead of category_id and user_name instead of user_id I try like these query It is work!
$articles =DB::table('articles') ->join('categories', 'articles.id', '=', 'categories.id') ->join('users', 'users.id', '=', 'articles.user_id') ->select('articles.id','articles.title','articles.body','users.username', 'category.name') ->get();
But I want to do by Eloquent way. Please, how could I do?
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
and you can use this like so:
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
You can learn more at http://laravel.com/docs/5.0/eloquent