我正在尝试显示突出显示中的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');
}
}
为了清楚起见,热切加载(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();