如何用腹语雄辩模型连接三表

我有三张桌子

文章表

 id
title
body
categories_id
user_id

分类表

  id
category_name

用户表

 id
user_name
user_type

我希望显示的文章使用它们的类别名称而不是 type _ id 和 user _ name 而不是 user _ id 我试着像这样询问,它是工作!

$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();

但是我想用雄辩的方式。请问,我能做什么?

296539 次浏览

With Eloquent it's very easy to retrieve relational data. Check out 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
    <?php
namespace App\Models;
use Eloquent;
    

class Article extends Eloquent {
protected $table = 'articles';
    

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

public function category() {
return $this->belongsTo('App\Models\Category');
}
}
  1. Category.php
    <?php
namespace App\Models;
    

use Eloquent;
    

class Category extends Eloquent {
protected $table = "categories";
    

public function articles() {
return $this->hasMany('App\Models\Article');
}
}
  1. User.php
    <?php
namespace App\Models;
use Eloquent;
    

class User extends Eloquent {
protected $table = 'users';
    

public function articles() {
return $this->hasMany('App\Models\Article');
}
}

You need to understand your database relation and setup in models. The user has many articles. The category has many articles. Articles belong to user and category. Once you set up 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

Try:

$articles = DB::table('articles')
->select('articles.id as articles_id', ..... )
->join('categories', 'articles.categories_id', '=', 'categories.id')
->join('users', 'articles.user_id', '=', 'user.id')


->get();
$articles =DB::table('articles')
->join('categories','articles.id', '=', 'categories.id')
->join('user', 'articles.user_id', '=', 'user.id')
->select('articles.id','articles.title','articles.body','user.user_name', 'categories.category_name')
->get();
return view('myarticlesview',['articles'=>$articles]);