gpt4 book ai didi

php - 显示表中的一列在 Laravel 中有很多关系

转载 作者:搜寻专家 更新时间:2023-10-31 21:47:11 25 4
gpt4 key购买 nike

在我的项目中,属性和视频之间有很多关系。我正在尝试显示属性表中的标题,其中该标题属于视频表中的相应视频。

properties (id, title)

videos (id, model_id, filename_video)

这里的 model_id 是指向属性表的外键。使用当前代码,我可以显示所有标题。任何帮助表示赞赏。这是我的代码。

属性.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Property extends Model
{
protected $guarded = ['id'];

public function videos()
{
return $this->hasMany(Video::class, 'model_id');
}
}

视频.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
protected $guarded=['id'];

public function properties()
{
return $this->belongsTo(Property::class);
}

}

PropertyController.php

public function viewVideos(Property $property, Video $video)
{
$results = DB::table('properties')
->join('videos', 'properties.id', '=', 'videos.model_id')
->select('properties.title')
->get();

$video = $property->videos;

return view('property.videos', compact('video', 'results'));
}

视频.blade.php

<h1 class="font-weight-light text-center text-lg-left mt-4 mb-0">
Videos for
@foreach($results as $result)
{{$result->title}}
@endforeach
</h1>

最佳答案

尝试这样设置:

Property.php

class Property extends Model
{
protected $guarded = ['id'];

public function video()
{
return $this->hasMany(Video::class);
}
}

Video.php

class Video extends Model
{
protected $guarded=['id'];

public function properties()
{
return $this->belongsTo(Property::class, 'model_id');
}
}

Controller

$results = Property::with('videos')->where('title', $property->title)->get();

关于php - 显示表中的一列在 Laravel 中有很多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57004190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com