Laravel数据透视表n:m关系


Laravel pivot tables n:m relationships

我有表organisations和另一个表clients。一个组织可以有多个客户端,一个客户端可以属于多个组织,因此有了多对多关系和数据透视表client_organisation

在我的模型Organisation.php中,我有以下内容,

class Organisation extends Eloquent {
    //Organisation __has_many__ clients
    public function clients()
    {
        return $this->hasMany('client');
    }
}

在我的Client.php模型中,我有

class Client extends Eloquent {
    public function organisations()
    {
        return $this->belongsToMany('organisation');
    }
}

透视表迁移,

use Illuminate'Database'Migrations'Migration;
use Illuminate'Database'Schema'Blueprint;
class CreateClientOrganisationTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('client_organisation', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('client_id')->unsigned()->index();
            $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
            $table->integer('organisation_id')->unsigned()->index();
            $table->foreign('organisation_id')->references('id')->on('organisations')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

然后在控制器中运行以下命令,以检索所有组织和客户,

$organisations = new Organisation;  
$organisations->clients()->get();

但是这会导致以下错误,

SQLSTATE[42S22]: Column not found: 1054 Unknown Column .日志含义在where子句中输入"clients.organisation_id"clients where clientsorganisation_id是null)

现在我的理解是,不应该在我的数据库中需要一个clients.organisation_id列,因为我有一个数据透视表,我做错了什么?我希望能够得到我所有的组织和他们的客户,使用透视表。

要使用数据透视表,您应该在关系的两端使用belongsToMany:

class Organisation extends Eloquent {
    public function clients()
    {
        return $this->belongsToMany('Client');
    }
}
class Client extends Eloquent {
    public function organisations()
    {
        return $this->belongsToMany('Organisation');
    }
}

注意,belongsToMany的第一个参数是类的名称,它是大写的。