如何在Laravel中创建双重has_many关系?

时间:2013-06-05 21:58:06

标签: database model migration laravel eloquent

我有一个包含Employee表和Customer表的数据库。 Employee表与Customer表有2个one_to_many关系; Customer表中的外键是'primary_sales_contact_id'和'primary_service_contact_id'。两者都明显引用Employee表上的id字段。 如何为此设置迁移,以及如何为其创建模型?我是Laravel的新手,如果它显得非常明显,那么道歉,感谢你的时间。

1 个答案:

答案 0 :(得分:2)

员工迁移

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEmpoyeeTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employee', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('name');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('employee');
    }

}

客户迁移

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCustomerTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customer', function(Blueprint $table)
        {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('name');
            $table->integer('primary_sales_contact_id')->unsigned();
            $table->integer('primary_service_contact_id')->unsigned();

            $table->foreign('primary_sales_contact_id')->references('id')->on('employee');
            $table->foreign('primary_service_contact_id')->references('id')->on('employee');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('customer');
    }

}

员工模式

class Employee extends Eloquent
{
    protected $table = 'employee';

    public $timestamps = false;

    public function customersService() {
        return $this->hasMany('Customer', 'primary_service_contact_id');
    }

    public function customersSale() {
        return $this->hasMany('Customer', 'primary_sales_contact_id');
    }
}

客户模式

class Customer extends Eloquent
{
    protected $table = 'customer';

    public $timestamps = false;

    public function primarySalesContact() {
        return $this->belongsTo('Employee', 'primary_sales_contact_id');
    }

    public function primaryServiceContact() {
        return $this->belongsTo('Employee', 'primary_service_contact_id');
    }
}

所有内容都使用如下:

$customer = Customer::find(1);
echo $customer->primaryServiceContact;
$employee = Employee::find(1);
echo $employee->customersSale;