【问题标题】:Laravel Eloquent get data where comparison is trueLaravel Eloquent 获取比较正确的数据
【发布时间】:2020-05-29 11:24:33
【问题描述】:

我正在为一家时装店创建一个迷你库存。我正在使用 Laravel/Voyager 和 BREAD,一切都很好。我有 2 个表 SizesProducts 有一个共同的列 product_code

我想从Sizes 获得结果,其中列product_code = Product 'product_code'。 我在控制器中有这个查询:

$product_code = Product::all();
$allSizes = Size::where('product_code', ($product_code->product_code));

在browse.blade.php我有:

@foreach ($allSizes as $size)
    <tr>
        <td align="right">{{$size->size_name}}</td>
        <td align="right">{{$size->stock}}</td>
    </tr>
@endforeach 

我猜where 语句没有按预期工作。 我想根据product_code 为表Sizes 中的每个尺寸获取相应的stock

【问题讨论】:

    标签: laravel eloquent voyager


    【解决方案1】:

    试试这个

    $product_code = Product::pluck('product_code')->toArray();
    $allSizes = Size::whereIn('product_code', $product_code)->get();
    

    在browse.blade.php中:

    @foreach ($allSizes as $size)
        <tr>
            <td align="right">{{$size->size_name}}</td>
            <td align="right">{{$size->stock}}</td>
        </tr>
    @endforeach 
    

    【讨论】:

    • 或者你也可以申请加入
    • 正在抛出 bac 错误 Trying to get property 'product_code' of non-object
    • 现在检查@fallcoshkoder
    【解决方案2】:

    我认为你的做法是错误的。您的表格在某种程度上相关,您需要定义一个关系Eloquent访问数据。

    如果我正在构建这样一个数据库,我认为ProductSize 之间的关系是many to many。 IE。一个Product可以有很多个Sizes,你也可以在某个Size中购买很多个Products。因此,您的模型之间应该具有belongsToMany() 关系。

    // Product.php
    protected $with = ['sizes'];     // eager load product sizes
    public function sizes() {
        return $this->belongsToMany(Size::class);
    }
    
    // Size.php
    public function products() {
        return $this->belongsToMany(Product::class);
    }
    

    那你就可以了

    // ProductsController.php
    public function show(Product $product) {
        return $product;
    }
    

    【讨论】:

      【解决方案3】:

      您错过了运行query

      $product_code = Product::all();
      # ::all() will return collection, and you can't access a property of it directly
      
      $allSizes = Size::where('product_code', ($product_code->first()->product_code))->get();
      

      注意 ->get();

      【讨论】:

      • 你注意到了。但现在我收到一个错误Property [product_code] does not exist on this collection instance.
      • 检查我更新的答案,你正在返回 Product::all();这将返回一个集合,所以你不能这样做 $product_code->product_code,因为 $product_code 是一个集合,你需要选择一个值
      • 明白,但正如您所说“不能这样做 $product_code->product_code,因为 $product_code 是一个集合”我将 product_code 作为变量。我试图得到的 SQL 语句是:SELECT * FROM sizes WHERE product_code=$product_code; 然后详细说明数据以获取每种产品的尺寸和每种尺寸的库存。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 2022-01-15
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多