[英]How to select specific column from a table that has one to many relationship with another table?
[英]Display one column from table in has many relationship in Laravel
我的項目在屬性和視頻之間有很多關系。 我試圖從屬性表中顯示標題,其中該標題屬於視頻表中的相應視頻。
properties (id, title)
videos (id, model_id, filename_video)
這里model_id是指向屬性表的外鍵。 使用當前代碼,我將顯示所有標題。 任何幫助表示贊賞。 這是我的代碼。
Property.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');
}
}
Video.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'));
}
videos.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');
}
}
調節器
$results = Property::with('videos')->where('title', $property->title)->get();
你應該試試這個:
$results = DB::table('properties')
->join('videos', 'properties.id', '=', 'videos.model_id')
->pluck('title');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.