Laravel Eloquent retrieve data from multiple tables
Solution 1
Completing @zippo_ answer, in the Controller
you must reference what tables you want, e.g.
User.php
use Article;
public function article()
{
return $this->hasOne('App\Article');
}
and in the e.g. UserController.php
$user = User::with('article')->get();
EDIT:
if you want to relate User to Article.Category, after create a relation with user and article
Article.php
use Category;
public function category()
{
return $this->hasOne('App\Category');
}
e.g. UserController.php
$user_articles_categories = User::with('article.category')->get();
Solution 2
You can take advantage of laravel eager loading, which are also called as Eloquent relationships.
Eloquent relationships are defined as functions on your Eloquent model classes.
Eg. In Article Model
public function article()
{
return $this->hasOne('App\Model\Category');
}
In this way, you need to define all the relationships in the respective Model classes.
for more info: http://laravel.com/docs/5.1/eloquent-relationships
user947668
Updated on June 19, 2022Comments
-
user947668 almost 2 years
I have four tables
**Articles table** id title body owner_id category_id **Favorite articles table** id user_id article_id **User table** id user_name user_type **Category table** id category_name
How to get list of favorite articles (article_name,owner_name,category_name) which related to currently logged user from db using laravel eloquent?
Is it possible to do it in single line request? e.g.:
$articles_data=Auth::user()->favorite_articles->article...
EDIT For the moment i have to use statement below:
$articles_data = FavoriteArticle::where('user_id', Auth::id())->join('articles', 'articles.id', '=', 'favorite_articles.article.id') ->join('users', 'users.id', '=', 'favorite_articles.user_id') ->join('categories', 'categories.id', '=', 'articles.id') ->get()
Which looks a bit complicated and doesn't use eloquent relations.