【问题标题】:Laravel Eloquent relation issue for multiple tables多个表的 Laravel Eloquent 关系问题
【发布时间】:2017-09-21 11:03:27
【问题描述】:

在 Laravel 5.5 中,我尝试创建一个小型应用程序来管理几个卖家/商店的产品。

因此,我有四种不同的模型:

卖家.php

class Attribute extends Model
{

    public function items()
    {

        return $this->belongsToMany(Item::class);
    }
}

项目.php

class Item extends Model
{

    public function seller()
    {

         return $this->belongsTo(Seller::class);
    }

    public function category()
    {

        return $this->belongsTo(Category::class);
    }

    public function attributes()
    {

        return $this->belongsToMany(Item::class);
    }
}

Category.php

class Category extends Model
{

    public function items()
    {

        return $this->hasMany(Item::class);
    }
}

属性.php

class Attribute extends Model
{

    public function items()
    {

        return $this->belongsToMany(Item::class);
    }
 }

对于属性和项目之间的多对多关系,我创建了一个数据透视表:

Schema::create('attribute_item', function (Blueprint $table) {
    $table->integer('attribute_id')->unsigned()->index();
    $table->foreign('attribute_id')->references('id')->on('attributes')->onDelete('cascade');
    $table->integer('item_id')->unsigned()->index();
    $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
    $table->primary(['attribute_id', 'item_id']);
});

整个应用程序的目标是:

  • 通过属性(用于过滤或其他)按类别获取卖家的所有商品
  • 获取卖家的特定商品并获取其属性和类别

我对 Laravel 关系方法以及在这种情况下使用哪种方法感到有些困惑。

hasManyThrough 还是多态关系更好?

我不得不承认我这里有一点逻辑问题。希望你能帮助我。

谢谢!

【问题讨论】:

  • 你的用户模型是什么?
  • 对不起,我描述的可能有点混乱。 “用户”是指卖方模型

标签: php laravel eloquent many-to-many relation


【解决方案1】:

您可以使用whereHas 方法查找嵌套关系,例如您的第一个目标

通过属性(用于过滤或其他)按类别从卖家那里获取所有商品

你可以这样写:

$items = Item::whereHas('seller.items', function ($query) {
        $query->whereHas('categories', function ($categories) {
            $categories->where('name', '=', 'Mens');
        })
        ->orWhereHas('attributes', function ($attributes) {
            $attriutes->where('size', '=', 'large');
        });
    })->get();

了解更多信息:https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence

如果您想获取具有类别和属性的项目,这将为您提供项目列表,您可以使用with 方法获取关系数据:

$items = Item::whereHas('seller.items', function ($query) {
        $query->whereHas('categories', function ($caegories) {
            $categories->where('name', '=', 'Mens');
        })
        ->orWhereHas('attributes', function ($attributes) {
            $atributes->where('size', '=', 'large');
        });
    })
    ->with('categories', 'attributes')
    ->get();

希望本文能指导您解决您面临的问题。

【讨论】:

  • 这几乎就是我想要的解决方案。老实说,我希望我可以通过执行以下操作来获取集合:$seller->items->attributes()$seller->items->category
  • 抱歉,在我识别出你已经编辑你的帖子之前发布了这个
  • 如果你喜欢这个答案,你可以接受并投票。
  • ->with(..) 可能是解决方案。我会试一试,在这里留下我的赞成/接受
  • 没问题,如果有什么问题请告诉我,我很乐意为您提供帮助。
猜你喜欢
  • 2014-05-24
  • 2019-06-23
  • 2015-06-27
  • 1970-01-01
  • 2021-06-19
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
相关资源
最近更新 更多