2017-02-25 80 views
0

我有Posts表。如何通过第三表Laravel选择?

每个Post有三类:

Post_categories 
_________________ 
id post_id | category_id 

也有表:

User_categories 
__________________ 
category_id | user_id 

所以,我需要从Post表中,选择所有行User_categories.user_id =9User_categories.category_id = Post_categories

所以,别人的话,我需要显示用户订阅的类别的文章。

回答

1

给予另一种尝试与雄辩的方式。

在Post模型类中,定义与Category模型的多对多关系。 (枢转表是Post_categories

class Post { 
public function categories() 
{ 
return $this->belongsToMany('App\Category', 'Post_categories', 'post_id', 'category_id'); 
} 
} 

在用户模型类,定义与分类模型中的多对多的关系。 (数据透视表是User_categories)同样在这个类中,将posts()函数定义为关系存在的查询。

class User { 
public function categories() 
{ 
return $this->belongsToMany('App\Category', 'User_categories', 'user_id', 'category_id'); 
} 

public function posts() 
{ 
return App\Post::whereHas('categories', function ($query) use($this) { 
$query->whereIn('posts.cat_id', array_column($this->categories->toArray(), 'categories.id')); 
}); 
} 

} 

要获得职位,用户订阅

App\User::find(9)->posts; 

希望这有助于。

+0

你可以去聊天? – Darama

+1

当然。当你周围发出嗡嗡声时。 –

+0

我在这里,放手 – Darama

0

我建议从这里阅读文档: https://laravel.com/docs/5.4/eloquent

这里: https://laravel.com/docs/5.4/eloquent-relationships

特别是这部分: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

首先你要定义的模型PostCategory ,和User

之后,确保根据您的需求定义正确的关系,但正如我从您的问题中了解的,您需要多对多的关系。 对于这种关系,您还需要创建数据透视表。按照惯例,您将它们命名为category_postcategory_user(从数据透视表中两个模型的小写名称,按字母顺序排列)

您的数据透视表迁移应该是这个样子,例如用于category_post

public function up() 
{ 
    Schema::create('category_post', function (Blueprint $table) { 
     $table->integer('category_id')->unsigned()->index(); 
     $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); 
     $table->integer('post_id')->unsigned()->index(); 
     $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); 
     $table->primary(['skill_id', 'user_id']); 
     $table->timestamps(); 
    }); 
} 

建立表格后,您必须确保关系正确定义。

之后,你应该能够做这样的事情:

User::find(9)->posts;

+0

不幸的是,但你没有得到我的问题,请看这个SQL:http://sqlfiddle.com/#!9/ec162/3/0 – Darama

+1

那么,答案仍然存在,你只需要适应'公告'而不是'发布' –

+0

我们可以去聊天吗? – Darama

相关问题