0

我有一个包含 Employee 表和 Customer 表的数据库。Employee 表与 Customer 表有 2 个 one_to_many 关系;Customer 表中的外键是“primary_sales_contact_id”和“primary_service_contact_id”。两者显然都引用了 Employee 表上的 id 字段。如何为此设置迁移,以及随后如何为其创建模型?我是 Laravel 的新手,如果它明显很明显,请道歉,并感谢您的时间。

4

1 回答 1

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;
于 2013-06-06T09:47:11.503 回答