【问题标题】:I am trying to mix pivot table values in Laravel我正在尝试在 Laravel 中混合数据透视表值
【发布时间】:2018-10-09 03:23:04
【问题描述】:

我有三个表类别和产品,其数据透视表为 category_product

一个类别有很多产品

我希望产品属性中的类别名称有自己的字段。

    $saijal = "Our Products";
    $products = Product::orderBy('created_at','DESC')->with('categories')->get();

    $abc = new Collection();
    foreach($products as $pro)
    {
        $abc->put($pro->id,$pro);
    }

    foreach($products as $k => $pro)
    {
        $abc->get($pro->id)->children = new Collection();
        $abc->get($pro->id)->categoryName= $pro->categories->name;

        $abc->get($pro->id)->children->push($pro);
        unset($pro[$k]);

    }
    dd($abc);

例如:

【问题讨论】:

  • 'category_name' ?产品有很多类别。

标签: php mysql database laravel eloquent


【解决方案1】:

如果我的理解正确,您希望能够直接从产品对象访问名为“categoryName”的属性。为此,只需在 Product.php 模型中设置一个属性 getter,如下所示:

public function getCategoryNameAttribute()
{
    return $this->category->name;
}

然后你可以像这样简单地引用类别名称:

$product->categoryName

我看到的主要问题是您在代码中引用“类别”,就好像它是复数一样。如果产品属于许多类别,则解决方案会有所不同,并且您的关系将需要数据透视表,如您所描述的。但是,如果产品只属于一个类别,正如您的代码所暗示的那样,上面的解决方案应该就足够了,您实际上不需要数据透视表。您只需在 products 表中直接有一个 category_id 列。

如果您确实希望每个产品有多个类别,您可以执行类似的操作,但返回一个数组:

public function getCategoryNamesAttribute()
{
    return $this->categories->pluck('name');
}

这将返回与此产品关联的类别名称数组,并可通过以下方式访问:

$product->categoryNames

【讨论】:

    【解决方案2】:

    您可以将自定义属性添加到appends 数组(不是attributes 数组)

    class Product extends Model
    {
    
        protected $appends = ['category_names'];
    
        public function getCategoryNamesAttribute()
        {
            return $this->categories->map->name;
        }
    }
    

    你可以访问这个属性,

    $product->category_names;
    

    注意

    将此添加到appends 数组的好处是。如果您不将此添加到 appends 数组中,当您调用 toArray()toJson() 或通过 json 发送此 $product 时。你失去了这个属性。

    【讨论】:

      猜你喜欢
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2018-04-10
      • 2020-05-28
      • 2020-08-09
      • 2021-10-03
      • 1970-01-01
      相关资源
      最近更新 更多