【问题标题】:eloquent only get first Active query雄辩只得到第一个主动查询
【发布时间】:2020-06-06 15:05:56
【问题描述】:

大家好,我有一个令人困惑的问题

我有 3 张桌子

  1. basket_lists(购物车)
  2. basket_items (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');
}

【问题讨论】:

  • dash ali ye mosbat behet dadam hal koni ;) chizi 是名品 nadareim。 chun har item faghat motalegh be ye product hast。 pas rabete hasMany() 食盐。 bayad 属于 bezari。
  • oon bande khoda ham dorost javab dade。年龄 kar nemikone shayad 到 product_Id ro product_id minevesi yeja。 be horufe kuchik va bozorg deghat kon

标签: php laravel eloquent laravel-blade


【解决方案1】:

你打破了 Laravel 外键 'product_Id' 的默认命名约定

一定是'product_id'

Eloquent 根据 型号名称。在这种情况下,BasketItem 模型会自动 假设有一个'product_id' 外键。如果你想覆盖这个 按照惯例,您可以将第二个参数传递给 hasMany 方法:

修复

应用\BasketItem.php

public function product()
{
    return $this->belongsTo(Product::class, 'product_Id','id' );
}

查看Documentation

用法

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

【讨论】:

  • 感谢您的回答!但这不是答案!我确实解决了这个问题,没有任何改变@FouedMOUSSI
  • 关于您的数据库模式,您必须在 BasketItem 模型中将 products() 方法关系从 hasMany 更改为 belongsTo。查看更新的答案
  • 注意区分大小写。 product_id 或 product_Id
【解决方案2】:

你必须改变你的关系为 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)
        }

【讨论】:

    猜你喜欢
    • 2020-01-14
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2014-09-16
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多