Laravel 3级雄辩查询关系



我想要一些帮助在Laravel Eloquent上形成查询

我的应用程序中有4个模型

<<p>项模型/strong>
class Item extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'code', 'name', 'type', 'price', 'cost', 'reorder_level', 'status'
];

public function grnoteitems()
{
return $this->hasMany(Grnoteitem::class);
}
}
<<p>Grnote模型/strong>
class Grnote extends Model
{
use HasFactory;
protected $fillable = [
'date', 'number', 'warehouse_id','user_id', 'authorized_id', 'approved_id', 'notes'
];
public function grnoteitems()
{
return $this->hasMany(Grnoteitem::class);
}
public function warehouse()
{
return $this->belongsTo(Warehouse::class);
}
}
<<p>Grnoteitem模型/strong>
class Grnoteitem extends Model
{
use HasFactory;
protected $fillable = [
'grnote_id', 'item_id', 'description', 'packing', 'quantity', 'price', 'total'
];
public function grnote()
{
return $this->belongsTo(Grnote::class);
}
public function item()
{
return $this->belongsTo(Item::class);
}
}

仓库模型

class Warehouse extends Model
{
use HasFactory;
protected $fillable = ['name', 'address'];
public function grnotes()
{
return $this->hasMany(Grnote::class);
}
}

项目的数量是通过grnotes表中的数量和包装列相乘来计算的。

现在我想从一个特定的仓库中检索所有物品及其数量(数量*包装)。

我累了下面的查询


$items = Item::withSum('grnoteitems',  'quantity', function($query) use($warehouse, $from, $to){
$query->with('grnote', function($query1) use($warehouse, $from, $to){
$query1->where('warehouse_id', $warehouse->id)
->whereBetween('date', [$from, $to])->get();
})->get();
})->get();

工作正常。但是我找不到两列相乘的和

我想要像

这样的东西
$items = Item::withSum('grnoteitems', '(quantity * packing)', function($query) use($warehouse, $from, $to){
$query->with('grnote', function($query1) use($warehouse, $from, $to){
$query1->where('warehouse_id', $warehouse->id)
->whereBetween('date', [$from, $to])->get();
})->get();
})->get();

请帮我解决这个问题。

写这么多代码有点长,但我的想法是:

  • 从您想要从
  • 中获取物品的仓库开始查询
  • so Warehouse::first() [with grnote [with item]]和custom where stuff
  • 那么你需要计算的数据是在Item和Grnote之间的数据透视表上,所以我将添加withPivot到这两个关系
  • 在此查询顺序中,枢轴值将作为关系追加到Item对象
  • 我将在项目模型中添加一个新属性。检查pivot属性是否已设置(因此它来自带有pivot的查询),计算数量,并将其附加到Item实例

您还可以循环生成的Collection以附加您的新属性。

最新更新