Laravel 5产品订单关系语法:不唯一的表/别名

时间:2018-11-22 11:21:30

标签: php laravel-5 eloquent syntax-error relationship

我正在开发可用于为产品定价清单的应用程序。
简而言之:一家餐馆有一个价目表,他们可以按照可插入新价格的流程进行更新。

结果将生成价格订单。

现在我想要的是我检索产品的所有类别(没问题),然后我要建立从产品到PriceOrderProduct的关系,所以我知道什么时候订单中使用了产品。

我现在有这个:

ProductCategory::with('products.orderProduct')->orderBy('order')->get() 

这给了我这个错误:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 

完整错误:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'price_order_products' (SQL: select `price_order_products`.*, `price_order_products`.`product_id` as `pivot_product_id`, `price_order_products`.`id` as `pivot_id` from `price_order_products` inner join `price_order_products` on `price_order_products`.`id` = `price_order_products`.`id` where `price_order_products`.`product_id` in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))

我已经搜索了此错误,但是不知道如何解决,有人可以帮我解决这个问题吗?

这些是我的表格和关系:

(我在表中使用price_前缀)

表:price_product_categories
-id
类别信息等

型号:ProductCategory

public function products()
{
    return $this->hasMany(Product::class, 'product_category_id');
}

=========================
price_products
-id
-product_category_id
产品信息等

型号:产品

public function categories()
{
    return $this->belongsTo(ProductCategory::class, 'product_category_id');
}


public function orderProduct()
{
    return $this->belongsToMany(PriceOrderProduct::class, 'price_order_products', 'product_id', 'id');
}

=========================
表格:price_orders
-id
-restaurant_id
等等

型号:PriceOrder

public function products()
{
    return $this->hasMany(PriceOrderProduct::class, 'order_id');
}

=========================
表price_order_products
-order_id
-product_id
-价格
-product_info

型号:PriceOrderProduct

public function orders()
{
    return $this->belongsTo(PriceOrder::class);
}

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

1 个答案:

答案 0 :(得分:1)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'price_products';

    public function categories()
    {
        return $this->belongsTo(ProductCategory::class, 'product_category_id');
    }

    public function orderProducts()
    {
        return $this->hasMany(PriceOrderProduct::class, 'product_id');
    }
}

这将对您查询所需的输出起作用。通过获得hasMany关系而不是belongsToMany。

相关问题