laravel eloquent pivot table查询“模糊列名”

时间:2015-07-03 11:29:13

标签: php sql laravel eloquent pivot-table

我正在尝试在两个表用户和产品之间创建一个数据透视表。但是,当我运行$user->Cart()->Get();时,我收到以下错误:

  

Connection.php第631行中的QueryException:SQLSTATE [HY000]:常规   错误:1个不明确的列名:main.cart.products_id(SQL:select   “cart”。*,“cart”。“user_id”as“pivot_user_id”,“cart”。“products_id”as   来自“购物车”内部的“pivot_products_id”加入“购物车”上的“购物车”。“id”=   “cart”。“products_id”,其中“cart”。“user_id”= 2)

这是用户模型:

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    ...

    public function Cart()
    {
        return $this->belongsToMany('App\Cart', 'cart', 'user_id', 'products_id');
    }
}

产品型号:

class Products extends Model
{
    ...
    public function Cart()
    {
        return $this->belongsToMany('App\Cart', 'cart', 'products_id', 'user_id');
    }
}

购物车型号:

class Cart extends Model
{
    //
    protected $table = 'cart';

    public function Products()
    {
        return $this->hasMany('App\Products', 'products', 'user_id', 'products_id');
    }


    public function User()
    {
        return $this->hasMany('App\Products', 'users', 'user_id', 'products_id');
    }
}

购物车架构:

        Schema::create('cart', function (Blueprint $table) {

        $table->integer('products_id')->unsigned();
        $table->foreign('products_id')->references('id')->on('products')
            ->onUpdate('cascade')->onDelete('cascade');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')
            ->onUpdate('cascade')->onDelete('cascade');
    });

1 个答案:

答案 0 :(得分:4)

在您的用户模型中,cart()方法应将App \ Product作为第一个参数:

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    public function carts()
    {
        // User can have many "products" in cart
        return $this->belongsToMany('App\Product', 'cart', 'user_id', 'products_id'); 
    }
}

产品相同:

class Product extends Model
{
    public function carts()
    {
        return $this->belongsToMany('App\User', 'cart', 'products_id', 'user_id');
    }
}

然后你的购物车型号:

class Cart extends Model
{
    protected $table = 'cart';

    public function product()
    {
        return $this->hasMany('App\Product', 'id', 'product_id');
    }


    public function user()
    {
        return $this->hasMany('App\User', 'id', 'user_id');
    }
}

PS:请注意,将模型类名称保持为Singular(产品非产品)和方法名称应以小写字母(购物车而不是购物车)开头是最佳做法