1

我正在使用 laravel 8,试图从相关模型中检索数据,这些模型返回除父模型之外的空数组。
我有 4 个模型

  1. 产品(父)
  2. 产品类别
  3. 产品属性
  4. 产品_照片



我正在获取这样的数据

$product = Product::select('name', 'description', 'price')
                          ->with(['categories' => function($query){
                                   $query->select(['category_id']);
                          }, 'attributes' => function($query){
                                   $query->select(['attribute_key',
                                                   'attribute_value']);
                          }, 'photos' => function($query){
                                   $query->select(['photo_path']);
                          }])
                          ->find($id);
return response()->json([$product]);

产品型号

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'user_id',
        'description',
        'price',
        'discount',
        'status'
    ];      

    /**
     * Get the photos of the product.
     */
    public function photos()
    {
        return $this->hasMany('App\Models\Product_photos');
    }

    /**
     * Get the attriutes of the product.
     */    
    public function attributes()
    {
        return $this->hasMany('App\Models\Product_attributes');
    }

    /**
     * Get the categories of the product.
     */
    public function categories()
    {
        return $this->hasMany('App\Models\Product_categories');
    }
}

这就是我得到的回应

[
    {
        "name": "Fendi FF motif zip-up hoodie",
        "description": "sample description",
        "price": 480,
        "categories": [],
        "attributes": [],
        "photos": []
    }
]

任何帮助都将是可观的

4

0 回答 0