How to join three table by laravel eloquent model

后端 未结 3 1848
悲&欢浪女
悲&欢浪女 2020-11-27 10:36

I have three table

Articles table

 id
 title
 body
 categories_id
 user_id

Categories table

  id
  category         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 11:16

    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)


    1) Article.php

    belongsTo('App\Models\User');
        }
    
        public function category()
        {
            return $this->belongsTo('App\Models\Category');
        }
    
    }
    

    2) Category.php

    hasMany('App\Models\Article');
        }
    
    }
    

    3) User.php

    hasMany('App\Models\Article');
        }
    
    }
    

    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:

    $article = \App\Models\Article::with(['user','category'])->first();
    

    and you can use this like so:

    //retrieve user name 
    $article->user->user_name  
    
    //retrieve category name 
    $article->category->category_name
    

    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:

    $categories = \App\Models\Category::with('articles')->get();
    
    $users = \App\Models\Category::with('users')->get();
    

    You can learn more at http://laravel.com/docs/5.0/eloquent

提交回复
热议问题