![](/img/trans.png)
[英]Laravel how to return the value NULL when hasMany relationship is empty
[英]How to merge hasMany relationships and return a relationship in Laravel?
我正在嘗試合並2個集合,因為我需要搜索多列記錄,即team_one_id
和team_two_id
具體取決於它是客場還是主場比賽。
嘗試合並它們時,會在函數matches
發生。 當我在第一個關系上調用merge
時,函數matches
不會返回實際關系,而是返回一個集合。
例外:
SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select count(*) as aggregate from `matches` where `matches`.`team_one_id` = 1 and `matches`.`team_one_id` is not null and `winning_team_id` = 1) union (select * from `matches` where `matches`.`team_two_id` = 1 and `matches`.`team_two_id` is not null))
碼:
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $primaryKey = 'id';
protected $table = 'teams';
public $timestamps = false;
protected $guarded = ['id'];
public function homeMatches() {
return $this->hasMany('App\Database\Match', 'team_one_id');
}
public function awayMatches() {
return $this->hasMany('App\Database\Match', 'team_two_id');
}
public function matches() {
return $this->homeMatches()->union($this->awayMatches()->toBase());
}
}
您可以嘗試以下方法:
public function matches() {
return $this->getRelationValue('homeMatches')->union($this->getRelationValue('awayMatches')->toBase());
}
由於homeMatches()函數返回一個Relation實例,但是dynamic屬性返回一個Collection。
雄辯的關系並非旨在匹配一個或另一個字段,而是被設計為具有一個外鍵。 您可以在方法內運行查詢以獲取所需的結果,而無需依賴關系。
如注釋中所述,如果您想重新使用該查詢,請將該邏輯包含在受保護的函數中。
protected function allMatchesQuery()
{
// This needs to be wrapped in a nested query or else your orWhere will not be contained in parentheses.
return Match::where(function($q) {
$q->where('team_one_id', $this->id)->orWhere('team_two_id', $this->id);
});
}
public function getMatches() {
return $this->allMatchesQuery()->get();
}
public function getRecentMatches() {
return $this->allMatchesQuery()->orderBy('date', 'DESC')->limit(10)->get();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.