2017-02-25 83 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

相關問題