如何在laravel中进行多对多关系查询
简介: 我使用的是laravel 5.6 我在多对多关系查询中遇到问题 我有两种型号:订单和购物车如何在laravel中进行多对多关系查询,laravel,laravel-5,relationship,Laravel,Laravel 5,Relationship,简介: 我使用的是laravel 5.6 我在多对多关系查询中遇到问题 我有两种型号:订单和购物车 代码: 购物车型号: class Cart extends Model { public function order() { return $this->belongsToMany(Order::class); } } 订单型号: class Order extends Model { public function carts(){
代码: 购物车型号:
class Cart extends Model
{
public function order()
{
return $this->belongsToMany(Order::class);
}
}
订单型号:
class Order extends Model
{
public function carts(){
return $this->belongsToMany(Cart::class);
}
}
购物车迁移:
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->nullable();
$table->integer('price')->nullable();
$table->integer('pass')->default(0);
});
}
问题: 如何获取其
通过
字段位于购物车=1
中的订单
谢谢 首先,由于您的购物车有许多订单,因此应使用s将关系命名为“订单” 你只展示了你的购物车迁移,所以我猜不出来,但拉威尔还希望你创建一个“购物车订单”透视表 如果我理解得很好,你可以这样做:
Order::whereHas('carts',函数($query){
$query->where('pass',1);
})->get();
您可以在Laravel文档中阅读更多关于Eloquent的多对多关系的信息。首先,由于您的购物车有许多订单,因此该关系应命名为带有s的“订单” 你只展示了你的购物车迁移,所以我猜不出来,但拉威尔还希望你创建一个“购物车订单”透视表 如果我理解得很好,你可以这样做:
Order::whereHas('carts',函数($query){
$query->where('pass',1);
})->get();
您可以在Laravel文档中阅读更多关于Elounce的多对多关系的信息。试试这样
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get all of the owning commentable models.
*/
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
class Video extends Model
{
/**
* Get all of the video's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
这个链接帮助你,
那样的话希望这对你有帮助。像这样试试
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get all of the owning commentable models.
*/
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
class Video extends Model
{
/**
* Get all of the video's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
这个链接帮助你,
那样的话希望这对您有所帮助。谢谢。是的,我有透视表。我运行你的代码。但我有一个错误:
“SQLSTATE[42S22]:找不到列:1054未知列'pass'位于'where子句'(SQL:select
orders*,
cart\u order
cart\u-id`aspivot\u-cart\u-id
,cart\u-order
aspivor\u-id
来自orders
内部连接cart\u-order
id上ordercart\u id
=1和pass
=1)`非常感谢。没问题:)如果您想了解更多关于whereHas()
方法的信息,非常详细,谢谢。是的,我有pivot表。我运行了您的代码。但是我有错误:SQLSTATE[42S22]:找不到列:1054未知列“pass”in“where子句”(SQL:select
orders*,
cart\u order
cart\u-id`aspivot\u-cart\u-id
,cart\u-order
aspivor\u-id
来自orders
内部连接cart\u-order
id上ordercart\u id
=1和pass
=1)`非常感谢。没问题:)如果您想了解更多有关whereHas()
方法的信息,请详细阅读。我使用多对多关系。使用订单号和购物车号??我想得到订单!!萨克斯。我使用多对多关系。使用订单号和购物车号??我想得到订单!!