Php laravel 5.6中的1对n关系

Php laravel 5.6中的1对n关系,php,mysql,laravel,Php,Mysql,Laravel,我有一个发票模型,我希望它有'n'的产品,所以在我的发票模型中,我放置了一个关系,有许多类似于下面 public function products(){ return $this->hasMany('App\Product','id','product_id'); } 所以在发票数据库中,我为产品创建了5个字段,并为每个产品创建了一个数量 $table->increments('id'); $table->text('title');

我有一个发票模型,我希望它有'n'的产品,所以在我的发票模型中,我放置了一个关系,有许多类似于下面

 public function products(){
    return $this->hasMany('App\Product','id','product_id');
}
所以在发票数据库中,我为产品创建了5个字段,并为每个产品创建了一个数量

 $table->increments('id');
        $table->text('title');
        $table->longText('description');
        $table->integer('client_id');
        $table->integer('product_id1');
        $table->integer('product_quantity1');
        $table->integer('product_id2')->nullable();
        $table->integer('product_quantity2')->nullable();
        $table->integer('product_id3')->nullable();
        $table->integer('product_quantity3')->nullable();
        $table->integer('product_id4')->nullable();
        $table->integer('product_quantity4')->nullable();
        $table->integer('product_id5')->nullable();
        $table->integer('product_quantity5')->nullable();
我想知道这样做是否正确,或者我应该制作一个包含产品id和发票id的表格,以便将它们相互结合???如果我必须做一个新表,我应该如何设置关系? 谢谢

这看起来类似于发票和产品之间的方法。添加连接发票和产品的连接表(发票产品),该表应具有
发票id
产品id
,还应具有每个产品的
数量的透视属性,如

对于多对多,您可以在模型中添加定义,如

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');
    }
}

谢谢@M khalid Junaid这是我的答案,但为了确定我是否应该为发票产品制作一个控制器或甚至是模型,或者只是做定义并将其存储在发票控制器中,然后从那里处理操作?谢谢again@Farshad不,您不需要为
invoice\u产品定义模型
只需使用laravel助手处理多对多的添加/更新操作谢谢khalid,我会尝试的。