in all one to one relationships, one table holds the key of the other. The model with the key belongsTo the other and the other hasOne of the model with the key
How to fix query One to One?
Have 2 tables Trailers and Tests with foreign id fields named "film_id" (in both tables). Want to bund them and take trailer, when download one of the tests page. One trailer belong to one test (it is like film, just in another name, 1 test = 1 film, which have 1 trailer).
I present to your attention a piece of code, because everything below does not matter, I'm trying to link tables in the first case cycle. And then everything will be connected in the same way.
public function result(Test $test, Film $film): View|string|\Illuminate\Database\Query\Builder
{
$url = url()->current();
$data1 = substr($url, -8, 1);
$data2 = substr($url, -7, 1);
switch ($data1) {
case 0: //GREY
switch ($data2) {
case 1: //GREY - BLUE
$array = DB::table('tests')->where([
['b','2'],
['d','1'],
['g','2'],
['h','1'],
]);
$trailer = Test::find($test->film_id)->trailer;
dd($trailer);
$tests = $array->simplePaginate(1);
$lazyloads = $array->simplePaginate(4);
return view('films.testing', ['tests'=>$tests, 'lazyloads'=>$lazyloads, 'film'=> $film, 'film_rate'=> $film->getRate(), 'trailer'=>$trailer]);
when I do DD command, there is show:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tests.id' in 'where clause'
select * from `tests` where `tests`.`id` is null limit 1
Bundle in Test model:
public function trailer(): HasOne
{
return $this->hasOne(Trailer::class, 'film_id');
}
Bundle in Trailer model:
public function trailer(): belongsTo
{
return $this->belongsTo(Trailer::class, 'film_id');
}
Of all the voiced, I'm wondering how to make this request correctly?
$trailer = Test::find($test->film_id)->trailer;
Thank you for helps, unfortunately not worked on my app, because I have a bad knows about relationships. I decide just one way, which fix this issue, hope it is a temporary solution)
In code above I added construction:
foreach ($tests as $test)
$film = $test->film_id;
$trailer = Film::find($film)->trailer;
now it looks
$tests = $array->inRandomOrder()->simplePaginate(1);
foreach ($tests as $test)
$film = $test->film_id;
$trailer = Film::find($film)->trailer;
$lazyloads = $array->simplePaginate(4);
return view('films.testing', ['tests'=>$tests, 'lazyloads'=>$lazyloads, 'film'=> $film, 'trailer'=>$trailer]);
Please or to participate in this conversation.