[英]Laravel how to join tables and use where condition using Eloquent?
可以說有2個表:
視頻(ID,文件名)
匹配項(id,videos_id,match_number)
我想通過match_number獲取視頻文件名。 我讀過,用口才,可以避免加入。
因此,我嘗試通過以下示例進行各種操作:
Video.php
class Video extends Eloquent {
protected $table = 'videos';
public function matches()
{
return $this->hasMany('Match', 'videos_id');
}
/*public function match()
{
return $this->belongsTo('Match', 'id');
}*/
/**
* @param $matchNumber
* @return mixed
*/
public function getByMatchNumber($matchNumber)
{
return $this
->matches()
//->select('videos.file_name')
//->limit(10)
->where('matches.match_number', $matchNumber)
->file_name;
// ->match()
}
}
但是沒有任何效果。
我想我很好地假設視頻具有很多匹配項,因為實際上有很多具有相同視頻的匹配項。
那么它應該看起來如何?
更新
Match_number列是唯一的,如id。 不能有多個具有相同比賽編號的比賽。 一場比賽只有一個視頻。 Limit(10)只是嘗試在沒有where條件的情況下嘗試以獲取數百萬個結果。 但是同一視頻分配給許多比賽。
更新:
我根據jedrzej.kurylo答案和我假設的固定錯誤(whereMatchNumber-這樣的功能將不存在)重新制作了該功能:
public function getByMatchNumber($matchNumber)
{
return Match::with('video')
->where('match_number', $matchNumber)->first(); //->video->file_name;
}
但這行不通。 我得到錯誤:
調用未定義的方法Illuminate \\ Database \\ Query \\ Builder :: video()
更新
在Match.php模型中,我添加了關系:
public function video()
{
return $this->belongsTo('Video', 'videos_id');
}
仍然出現相同的錯誤:
調用未定義的方法Illuminate \\ Database \\ Query \\ Builder :: videos()
更新:我有一個錯誤,當發生gettign錯誤並試圖撤消時嘗試添加復數形式:
return Match::with('videos')
需要:
return Match::with('video')
更新
仍然無法獲得結果。 我運行這個:
$video = $this->video->getByMatchNumber($this->matchNumber);
print_r($video->file_name);
我在查詢日志中看到好的查詢:
[1] => Array
(
[query] => select * from `matches` where `match_number` = ? limit 1
[bindings] => Array
(
[0] => 104439
)
[time] => 4.62
)
[2] => Array
(
[query] => select `file_name` from `videos` where `videos`.`id` in (?)
[bindings] => Array
(
[0] => 1089
)
[time] => 37.24
)
我在HeidySQL中使用綁定執行了最后一個查詢,並找到了結果。 那么為什么$ video-> file_name可以為空?
更新
我也嘗試過
die($video->video->file_name);
並得到錯誤
試圖獲取非對象的屬性
首先,使用Eloquent並不是要擺脫聯接,而是要使用對象表示法更輕松地操作數據。 根據使用方式的不同,您將使用聯接或不聯接來獲取數據。 只要正確使用聯接,使用聯接也沒有錯。
為了實現您所需要的,最簡單的方法是:
$match = Match::with('video')->whereMatchNumber($number)->first();
if ($match) {
echo $match->video->file_name;
}
但是,這將在數據庫中運行2個查詢。 如果要使用一個查詢執行此操作,則需要使用聯接:
$match = Match::join('videos', 'matches.videos_id', '=', 'videos.id')->whereMatchNumber($number)->first();
if($match) {
echo $match->file_name;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.