如何在laravel中获取外键表的值

时间:2014-09-29 06:34:09

标签: join laravel-4 foreign-keys

您好我正在尝试获取引用2个表的表的值。我的表看起来像这样

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 个答案:

答案 0 :(得分:1)

好吧,错误是不言自明的,你在查询中有一个语法错误,那是因为var $ page_id等于&lt; p&gt;主页&lt; / p为H. (出于某种原因)。

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
}