【问题标题】:LARAVEL - How to get attribute of a modelLARAVEL - 如何获取模型的属性
【发布时间】:2017-06-10 18:40:12
【问题描述】:

如何获取每个产品类别的类型名称?

示例
类别:CAT1 / CAT2。
产品:name1(类型:type1、type_id & categorie_id 外键)
名称2(类型:类型2)
类型:type1
类型2

用于制作一个类别菜单,其中包含该类别的“子菜单”类型(foreach)

我已经尝试过了,但不起作用(未定义属性:Illuminate\Database\Eloquent\Collection::$type)。只是 $cat->produit 工作,但这不是我想要的:

$categories = Categorie::All();        

@foreach ($categories as $cat)   
               {{$cat->nom}}
               <ul>
                   @foreach ($cat->produit->type as $type)
                         <li><a href="#">{{$type->nom}}</a></li>                                               
                   @endforeach
              </ul>
@endforeach

[TYPE] 1,n(have)1,1 [PRODUCT] 1,1(To-belong)1,n [CATEGORIE]

产品

public function Categorie()
{
    return $this->belongsTo('App\Models\Categorie');
}
public function Type()
{
    return $this->belongsTo('App\Models\Type');
}

类别

public function Produit()
{
    return $this->hasMany('App\Models\Produit');
}

类型

public function Produit()
{
     return $this->hasMany('App\Models\Produit');
}

【问题讨论】:

  • Product 模型中的type 是包含类型名称的列?
  • 产品:id、name、type_id、categorie_id
  • 谢谢,我已经在下面发布了答案。

标签: sql laravel model eloquent


【解决方案1】:

使用 Eloquent 实现这一目标的最有效方法是这种仅使用 3 次查询从 DB 获取数据的方法。然后它使用 Laravel 集合的强大功能:

// Get data from DB.
$categories = Categorie::with('products')->get();
$types = Type::all();

// Working with loaded collections.
@foreach ($categories as $category)
    {{ $category->name }}
    @foreach ($types->whereIn('id', $category->products->unique('type_id')->pluck('type_id')) as $type)
        {{ $type->name }}
    @endforeach
@endforeach

【讨论】:

  • 我有一个唯一性错误:Builder.php 第 2450 行中的 ErrorException:调用未定义的方法 Illuminate\Database\Query\Builder::unique()(查看:..)编辑:你'已经编辑了你的帖子,或者我很糟糕,删除了一个字。但它什么也没返回
  • @emeliku 那是因为它应该是with('products') 而不是with('product')。抱歉打错了。
  • 它是 $category->product->unique。但它没有返回任何视图
  • 应该是products
  • 啊,它从一开始就有效!但是我没有用“nom”替换视图属性中的“name”->它的法语名称,我的数据库是法语的!谢谢
猜你喜欢
  • 1970-01-01
  • 2014-05-04
  • 2021-11-19
  • 1970-01-01
  • 2016-02-04
  • 2017-02-20
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多