2014-09-29 65 views
0

您好我想獲得引用2個表的表的值。我的表看起來像這樣如何獲得laravel中的外鍵表的值

pages_content table 

page_id | content_id 
------------------------ 
1  |  4 
6  |  10 

pages table 

id | title 
----------------- 
1 | home 
6 | contact 


content table 


id | content 
----------------- 
4 | home page 
10 | contact us  

我需要引用pages_content表並獲取其他表中的值。 我想這

$content = DB::select('select * from pages_content pxc, content c where page_id = '.$page_id.' and content_id = c.id'); 

,我得到了一個語法錯誤

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<p>home page</p> and content_id = c.id' at line 1 (SQL: select * from pages_content pxc, content c where page_id = <p>home page</p> and content_id = c.id) (View: /Applications/MAMP/htdocs/test/app/views/public/content.blade.php) 

我也嘗試了幾件事情。如果你需要我提出其他的我已經嘗試過的或者如果你需要更多的信息,請告訴我

回答

1

那麼,錯誤是不言自明的,你在查詢中有一個語法錯誤,那是因爲var $ page_id等於< p>主頁</p>(出於某種原因)。

right syntax to use near '<p>home page</p> and content_id = c.id' at line 1 

另外,爲什麼不使用Eloquent而不是原始查詢(假設這是一個多對多的關係)?

$contents = Page::find($page_id)->content; 

foreach($contents as $c){ 
    $c->pivot->created_at //or whatever you want to access 
}