Lets say there are 2 tables:
videos (id, file_name)
matches (id, videos_id, match_number)
I want to get video file_name by match_number. I have read that using eloquent, you can avoid joins.
So I try various things from examples like this:
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()
}
}
But nothing works.
I think I am assuming well that video hasMany matches because in reality there are many matches which have same video.
So how it should look?
Update
Match_number column is unique, like id. There cannot be multiple matches with same match number. And there is only one video for one match. Limit(10) just was doing to try without where condition, to not get millions of results. But same video is assigned to many matches.
Update:
I remade the function based on the jedrzej.kurylo answer and fixed mistakes I assume - whereMatchNumber - such function will not be existing:
public function getByMatchNumber($matchNumber)
{
return Match::with('video')
->where('match_number', $matchNumber)->first(); //->video->file_name;
}
But it does not work. I get error:
Call to undefined method Illuminate\Database\Query\Builder::video()
Update
In Match.php model I added relation:
public function video()
{
return $this->belongsTo('Video', 'videos_id');
}
Still getting the same error:
Call to undefined method Illuminate\Database\Query\Builder::videos()
Update: I had a mistake, was trying to add plural form when gettign error and forgot to undo:
return Match::with('videos')
needed:
return Match::with('video')
Update
Still not able to get result. I run this:
$video = $this->video->getByMatchNumber($this->matchNumber);
print_r($video->file_name);
I see good queries in query log:
[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
)
I executed last query with the binding in HeidySQL and result is found. So why $video->file_name could be empty?
Update
Also I tried
die($video->video->file_name);
and get error
Trying to get property of non-object