【问题标题】:How to show value from laravel eloquent relationship如何从 laravel 雄辩的关系中显示价值
【发布时间】:2020-11-12 05:21:30
【问题描述】:

我有这样的表

products - id, name, description, category_id, brand_id, color_id, material_id, price
extras - id, product_id, size_id, stock
images - id, product_id, name, path
size - id, name

模型产品:

public function extra()
{
    return $this->hasMany('App\Extra', 'product_id', 'id');
}

public function image()
{
    return $this->hasMany('App\Image', 'product_id', 'id');
}

模型额外:

public function size()
{
    return $this->hasOne('App\Size', 'id', 'size_id');
}

public function product()
{
    return $this->belongTo('App\Product', 'product_id', 'id');
}

模型图片:

public function product()
{
    return $this->belongsTo('App\Product', 'product_id', 'id');
}

如何从 extras 和 images 表中获取尺寸名称、图像名称和路径值? 我可以使用此查询 echo $product['extra'][0]['size']['name']; 获取尺寸名称,但我只得到一个我不知道的值如何循环获取所有值。

$products = Product::with(['brand', 'category', 'color', 'image', 'material', 'extra', 'user'])->get();
foreach ($products as $product)
{
echo $product['name'] ." ". strip_tags($product['description']) ." ". $product['category']['name'] ." ". $product['brand']['name'] ." ". $product['color']['name'] ." ". $product['material']['name'] ." ". $product['price'] ." ". $product['sku'] ." ". $product['user']['name'] ."</br>";
echo $product['extra'][0]['size']['name'];
}

有什么建议我需要做什么或我可以阅读以解决这个问题吗?谢谢。

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    我相信下面的代码对你有用:

    // Extra relationship in Product.php
    public function extra()
    {
        return $this->hasMany('App\extra', 'product_id', 'id');
    }
    
    // To get product extra with eager loading 
    $products = Product::with(['extra', 'extra.size'])->get();
    
    foreach ($products as $product)
    {
      foreach ($product->extra as $extra){
        echo $extra->size->name
      }
    }
    

    【讨论】:

    • 对不起,图片价值怎么样,我想要的图片价值变成了产品数据的一行。 1 个产品有很多图像。怎么做?因为如果我对图像做同样的事情,结果会变成这样:名称等,大小,image1;名称等,大小,image2;名称等,大小,image3;我想要的是:名称等,大小,image1,image2,image3;
    • foreach ($products as $product) { foreach ($product->image as $sinleImage){ echo $sinleImage->name; echo $sinleImage->path } }
    • 它不工作,我试过然后结果是一样的变成这样:名称等,大小,image1;名称等,大小,image2;名称等,大小,image3;
    • @gigi 你的问题有点混乱请详细说明。 (图像值怎么样,我想要的图像值与产品数据变成一行。1个产品有很多图像。如何做到这一点?)
    • 我很抱歉我的英语不好。我现在会尝试解释一下,如果我执行程序,结果是产品名称等,尺寸,image1;产品名称等,尺寸,图像2;。我需要的是产品名称等,尺寸,image1,image2;。我将使用该数据显示在数据表中。解释可以理解吗?如果解释让您感到困惑,对不起。或者关于数据库设计的任何建议?我应该将数据图像与产品表放在一起,以便我可以删除图像表吗?
    【解决方案2】:

    产品包含您实现“与”的每个关系的多个值,因此请运行 foreach 循环或针对特定结果尝试此操作
    $products-brand->where("SOME CONDITION")->get();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 2015-03-14
      • 2018-11-28
      • 2015-01-11
      • 2021-06-03
      • 2020-03-26
      相关资源
      最近更新 更多