php - eloquent 只获取第一个 Active 查询

标签 php laravel eloquent laravel-blade

嘿伙计们,我有一个令人困惑的问题

我有3张 table

  1. basket_lists(购物车)
  2. 购物篮项目 (carts_item)
  3. 产品

通过此迁移

 'basket_lists':
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->boolean('active');
        $table->timestamps();


    basket_items:
        $table->bigIncrements('id');
        $table->unsignedBigInteger('product_Id');
        $table->unsignedBigInteger('basket_list_id');
        $table->timestamps();


       products:
        $table->bigIncrements('id');
        $table->string('title');
        $table->text('description');
        $table->bigInteger('amount');
        $table->timestamps();

当我搜索(查询)时,我的表格中有一些产品{

BasketList::where('active', '=', 1)->with('basketItems.products')->get();

它只给我第一个购物篮产品(其中 id = 1) 如果我插入新的购物篮列表并将第一个购物篮列表设置为 (active = 0),将第二个购物篮列表设置为 (active = 1),它将不会显示任何产品。

这是我的模型类:

class BasketList extends Model
{
    public function basketItems()
    {
        return $this->hasMany(BasketItem::class ,'basket_list_id' );
    }
}

class BasketItem extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class,'id' );
    }


    public function basketList()
    {
        return $this->belongsTo(BasketList::class);
    }

}


public function basketItem() 
{
    return $this->belongsTo(BasketItem::class ,'product_id');
}

最佳答案

您必须更改与belongsTo()的关系

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

    class BasketItem extends Model
    {
        //
        protected $table = 'basket_items';


        public function product()
        {
                return $this->belongsTo(Product::class, 'product_id','id' ); // Watch out for the case sensitive. how did you wright product_id in your migration. (product_id or product_Id)
        }

关于php - eloquent 只获取第一个 Active 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60351284/

相关文章:

php - 如何发现sql注入(inject)漏洞?

php - 如何通过 API 使用 PHP 获取 Instagram 照片?

php - 动态 FormRequest 验证 (Laravel)

laravel - 如何从 Laravel Controller 发布自定义值

php - 为什么 mcrypt_encrypt() 将二进制字符放在字符串的末尾?

php - 我想为图像区域提供绿色和红色

php - Laravel 5.1 Ajax 调用 'Like' 系统没有发生

php - 尽管文件存在,但 laravel 存储存在返回 false

MySQL : How to identify users I follow or follow me from other person's followers?

laravel - Laravel 中通过多对多关系模型对 eloquent 模型进行排序