[英]Laravel 4 SQL error when joining tables
我正在嘗試從突出顯示中顯示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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.