我对这个雄辩的想法有点陌生(数据透视/中间表格)。
我正在使用Laravel5.3,这些文档有点道理,但还不够。不幸的是!
我有几种方案想试着从.
我有以下DB表
在我的场景中,以下是关于这些DB表的说明..。
一家公司可以向提供许多优惠。
一家公司可以拥有许多属性
报价可以与许多公司联系在一起。
属性可以与许多公司相关联。
我已经创建了对应于5个DB表的5个模型。
我正在努力弄清楚,我是如何把这些关系融入我的模型的?
谢谢!
发布于 2016-10-04 14:58:18
您希望使用belongsToMany关系。例如:
class Company extends Model
{
    public function offers()
    {
        return $this->belongsToMany(App\Offer::class);
    }   
}如果您已经使用company_id和offer_id设置了枢轴表,这种关系将自动工作,并且将自动使用company_offer (按字母顺序排列的模型名称的单数版本)的枢轴表。如果您没有遵循命名约定,您可以指定pivot表和外键,如下所示:
return $this->belongsToMany('App\Offer', 'Company_Offers', 'Company_ID', 'Offer_ID');发布于 2016-10-04 14:55:13
实际上,在laravel中,您不必为枢轴表创建模型。因此,你可以选择三种模式,它们看起来更不像这样:
<?php
/* /app/Company.php */
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
    /**
     * The offers that belong to the company.
     */
    public function offers()
    {
        return $this->belongsToMany('App\Offer');
    }
     /**
     * The attributes that belong to the user.
     */
    public function attributes()
    {
        return $this->belongsToMany('App\Attribute');
    }
}
<?php
/* /app/Offer.php */
namespace App;
use Illuminate\Database\Eloquent\Model;
class Offer extends Model
{
    public function companies()
    {
        return $this->belongsToMany('App\Company');
    }
}
<?php
/* /app/Attribute.php */
namespace App;
use Illuminate\Database\Eloquent\Model;
class Attribute extends Model
{
    public function companies()
    {
        return $this->belongsToMany('App\Company');
    }
}关于如何使用它选择或更新这些关系的更多信息,您可以在这里找到:https://laravel.com/docs/5.3/eloquent-relationships#many-to-many
https://stackoverflow.com/questions/39855109
复制相似问题