Php 多对多关系库存发票
我试图在laravel中为我的发票和产品模型建立多对多关系,并将它们保存在povet(junken)表中,但我在获取关系时得到了库存,并将它们显示在前面,因此下面是代码 在我的发票模型中Php 多对多关系库存发票,php,laravel,Php,Laravel,我试图在laravel中为我的发票和产品模型建立多对多关系,并将它们保存在povet(junken)表中,但我在获取关系时得到了库存,并将它们显示在前面,因此下面是代码 在我的发票模型中 public function products(){ return $this->belongsToMany('App\Product','invoice_products','id','id'); } 在我的产品模型中 public function invoice() { ret
public function products(){
return $this->belongsToMany('App\Product','invoice_products','id','id');
}
在我的产品模型中
public function invoice() {
return $this->belongsToMany('App\Invoice','invoice_products','id','id');
}
“我的发票\产品”表的迁移
Schema::create('invoice_products', function (Blueprint $table) {
$table->increments('id');
$table->integer('invoice_id');
$table->integer('product_id');
$table->integer('product_quantity');
$table->timestamps();
现在,在我的控制器中,我想检索所有id为“1”且产品id为“2”的发票,例如,我想在视图中显示它们。我认为查询生成器是
$invoice = \App\Invoice::findOrFail(1);
该查询将按id查找发票数据
如果要选择产品的指定id
$products = $invoice->products()->where('id', 2);
// this for getting pivot
$qty = $products->pivot->product_quantity
如果您想从发票中获取所有产品
$products = $invoicce->products;
该查询将按最初选择的发票获取产品数据。通过查看您的迁移,您的映射看起来很奇怪,应该是这样的
class Invoice extends Model
{
public function products()
{
return $this->belongsToMany(Product::class, 'invoice_products', 'invoice_id')
->withPivot('quantity')
->as('invoice_products_pivot');
}
}
class Product extends Model
{
public function invoices()
{
return $this->belongsToMany(Invoice::class, 'invoice_products', 'product_id');
}
}
现在,要获取与product id=2链接的所有发票,您可以使用whereHas
filter
$product_id = 2;
$invoices= Invoice::whereHas('products', function ($query)use ($product_id) {
$query->where('id', '=', 'foo%');
})->get();
要按发票对象加载产品,您可以使用和
$product_id = 2;
$invoices= Invoice::with('products')->whereHas('products', function ($query)use ($product_id) {
$query->where('id', '=', 'foo%');
})->get();
我猜您的意思是检索id为2的产品的所有发票?而且您的映射看起来不正确id,id
?@M khalid junaid再次感谢khalid您的回答一如既往地完整而清晰:)但我还有一个问题是,主键的命名约定,例如,对于产品,我应该使用在laravel中更标准的id还是产品id?我认为命名约定应该可读,就像有保存在invoice\u products
中的产品应称为product\u id
发票参考invoice\u id
,id
通常用于主键符号,因此表中外键的格式类似于referencedtable\u pkcolumnofreferencedtable
类似于product\u id
@m khalid junaid是的,这是我在其他表中的问题,例如product table中我应该将id或product\u id作为主键吗??@Farshad表主键应命名为id
,以确保可读性,product\u id
应在链接产品表的其他表中使用