【问题标题】:Display one column from table in has many relationship in Laravel在 Laravel 中有很多关系的表格中显示一列
【发布时间】:2019-07-12 09:31:28
【问题描述】:

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

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'));
}

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>

【问题讨论】:

  • 您到底在显示什么?带有属性标题或属性列表的视频列表?
  • @Karan 我有那个页面视频,其中列出了该属性的所有视频。我正在尝试在页面顶部显示该属性的标题。例如,“该属性的标题”的视频。 '
  • 你得到什么结果查询的输出?
  • @Karan Collection {#297 ▼ #items: array:2 [▼ 0 => {#307 ▼ +"title": "aaaaaaaaaaaaaaaaaaaa" } 1 => {#304 ▼ +"title" :“这是项目一的标题!!!” } ] }
  • @Karan 或者简单地说,来自不同属性的标题。我需要一个特定的标题。在这种情况下,“项目一的这个标题!!! '

标签: php laravel has-many


【解决方案1】:

尝试这样设置:

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();

【讨论】:

  • 我得到 Column not found: 1054 Unknown column 'videos.property_id' in 'where Clause' (SQL: select * from videos where videos.property_id = 22 and videos .property_id 不为空)
  • 您的property 应该有一个视频。再次检查答案我更新了它
  • 我从不同的属性中获取标题,而我只需要该特定属性的标题
  • 在您的查询中等待您拥有所有数据,因为您拥有-&gt;get(),如果您想要一个标题,请使用-&gt;find() of -&gt;first() 指定哪个标题
  • 当我使用 first() 时,所有属性都会得到相同的结果。我需要属于该属性的标题
【解决方案2】:

你应该试试这个:

$results = DB::table('properties')
       ->join('videos', 'properties.id', '=', 'videos.model_id')
       ->pluck('title');

【讨论】:

  • 我得到 Trying to get property 'title' of non-object 错误
猜你喜欢
  • 2016-10-12
  • 2016-05-09
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2014-07-10
  • 2018-11-06
  • 2015-08-05
相关资源
最近更新 更多