我已經花了幾個小時試圖弄清楚這一點,我希望有人能幫助..問題與1-多Laravel雄辯模型查詢
我只是想輸出文章的標題與文章的平均等級爲每個。我已經建立了數據庫表文章和評級來保存數據,在評級表中我有rating_id,primary和article_id作爲鏈接到Articles表[主鍵]的外鍵。
我已創建爲每個表的模型和文章和評級模型之間的一對多關係:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $table = 'articles';
protected $primaryKey = 'article_id';
/**
* Define a 1-many relationship in eloquent
*/
public function ratings()
{
return $this->hasMany(Rating::class);
}
}
我還設置(等級和文章模型之間的反比關係是實際需要?): - 應該有2條記錄返回,這是你的第2個評級
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Rating extends Model
{
protected $table = 'rating';
protected $primaryKey = 'rating_id';
/**
* Define a 1-many inverse relationship in eloquent
*/
public function articles()
{
return $this->belongsTo(Article::class);
}
}
在我的控制,我通過「收視率」屬性,其中的article_id = 2調用收視率的集合。代碼示例:
public function ShowRating() {
$ratings = Article::find(2)->ratings;
var_dump($ratings);
}
我收到SQL錯誤,是我的模型關係不正確嗎?代碼示例:
> QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not
> found: 1054 Unknown column 'rating.article_article_id' in 'where
> clause' (SQL: select * from `rating` where
> `rating`.`article_article_id` = 2 and `rating`.`article_article_id` is
> not null)
一旦我管理了這個階段,我可以使用avg方法對評分進行平均。
提前道歉 - 我相信這是愚蠢的,但我無法弄清楚。非常感謝..
我是很新的larvel。我很困惑這篇article_article_id從哪裏來?你可以嘗試在hasMany和belongsTo函數的第二個參數中添加外鍵。返回$ this-> hasMany(Rating :: class,'rating_id');並返回$ this-> belongsTo(Article :: class,'rating_id'); (它應該是公共領域) – Farsay
在您的Article模型中嘗試'返回$ this-> hasMany(Rating :: class,'article_id')'。 –
謝謝Fairsay&Taylor Foster - HasMany方法缺少指定評級表中的外鍵的參數,在這種情況下,該參數爲'article_id'。然而,仍然不完全在那裏..使用下面的急切加載我可以得到文章標題和評分數據,但是當我嘗試訪問rating_score或任何其他特定的字段時,我得到'Property [rating_id]在此收集實例上不存在「。錯誤。語法錯誤? $ articles = Article :: all(); ($ articles as $ article){ echo $ article-> ratings-> rating_score; echo $ article-> headline; }' – pfeatherstone