我试图在精彩集锦中显示1条记录,同时将服务和页面加入此表格以显示其详细信息(而不是仅显示service_id
和page_id
)
在我的HighlightsController中,我有以下内容从我的数据库中获取项目:
$highlight = Highlight::where('id', $id)->with(array('Service','Page'))->get();
我收到此错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'services.highlight_id' in 'where clause' (SQL: select * from `services` where `services`.`highlight_id` in (1))
我知道这个专栏不存在,因为它正在查找错误的表格。我不知道我做错了什么。我已经一遍又一遍地用我的SQL模拟它并思考我哪里出错了
以下是可能有用的所有细节:
我想要的SQL:
SELECT * FROM highlights
LEFT JOIN pages ON pages.id = highlights.page_id
LEFT JOIN services ON services.id = highlights.service_id
WHERE highlights.id = '1'
我的桌子:
亮点
+------------+
| Field |
+------------+
| id |
| service_id |
| page_id |
| text |
+------------+
服务
+------------+
| Field |
+------------+
| id |
| title |
| description|
+------------+
网页
+------------+
| Field |
+------------+
| id |
| name |
+------------+
模型及其功能:
class Highlight extends Eloquent
{
function Service(){
return $this->HasMany('Service');
}
function Page(){
return $this->HasMany('Page');
}
}
class Service extends Eloquent
{
function Highlight(){
return $this->HasMany('Highlight');
}
}
class Service extends Eloquent
{
function Highlight(){
return $this->belongsTo('Highlight');
}
}
答案 0 :(得分:0)
要说清楚 - 急切加载(with()
方法)不会加入任何内容,但会为每个加载的WHERE id IN
子句关系运行另一个查询。
更改这些关系,因为它们完全不正确:
// Let's call methods snakeCased just for clarity and sticking to the convention
// and singular or plural depending on what is returned
class Highlight extends Eloquent
{
function service(){
return $this->belongsTo('Service'); // returns single Model
}
function page(){
return $this->belongsTo('Page'); // same as above
}
}
class Service extends Eloquent
{
function highlights(){
return $this->HasMany('Highlight'); // returns Collection of Models
// you can have hasOne instead, depending on your app
}
}
class Service extends Eloquent
{
function highlights(){
return $this->hasMany('Highlight'); // again Collection
}
}
然后你称之为:
// returns Collection, so let's call it plural:
$highlights = Highlight::where('id', $id)->with(array('service','page'))->get();