我正试图在用户和产品这两个表之间创建一个透视表。然而,当我运行$user->Cart()->Get();
时,我会得到以下错误:
Connection.php第631行中的QueryException:SQLSTATE[HY000]:常规错误:1个不明确的列名:main.cart.products_id(SQL:select"cart"。"user_id"替换为"pivot_user_id"、"cart"。"products_id"为"cart"内部的"pivot_products_id"将"cart"连接到"cart上"。"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');
});
在用户模型中,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(Product而非Products(,方法名称应以小写字母(carts而非carts(开头