2014-10-03 84 views
0

你好,我有以下3個表格,它們與ID相互關聯如下,我試圖在Laravel中爲每個表格創建一個模型,但我很困惑如何使用belongsTo &其他...Laravel 3表模型關係結構

TABLE: posts 
----------------------------- 
id  Auto-inc 
type_id if (3 its for a blog) 
title 
content 

TABLE: blog 
----------------------------- 
id  Auto-inc 
post_id the post id 
cat_id blog_cat table id 
slug 


TABLE:blog_cat 
----------------------------- 
id Auto-inc 
cat_name 

現在我嘗試寫blog.php的模型,BlogCat.php & post.php中,在那裏我可以用這樣的:

$blog = Post::with('blogCat')->get()->toArray(); 

獲取數組與崗位&我f type_id = 3(博客)也可以從博客表中獲取博客信息的數組,這是可能的,或者我只需要使用select,where/Join?

感謝

回答

0

在您的博客模式,你需要一個返回屬於關聯貓()的關係()。

在您的發佈模型中,您需要一個返回HasOne()的blog()關係。

要獲得職位的集合與博客渴望加載:

$blog = Post::with('blog')->get() 

要獲得職位的集合與博客渴望加載和BlogCats渴望加載每個博客:

$blog = Post::with('blog.blogCat')->get() 

爲了只加載博客的type_id爲3的帖子,您需要使用「eager load constraint

+0

BelongTo()究竟我在這裏困惑了什麼? – user3150060 2014-10-03 23:32:34

+0

你說博客模型和你的例子說Post :: with('blog') – user3150060 2014-10-03 23:33:41

+0

你的意思是這個$ blog = Blog :: with('post') - > get() - > toArray(); – user3150060 2014-10-03 23:39:30