首页 文章

Laravel透视表n:m关系

提问于
浏览
0

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

}

数据透视表迁移,

<?php

使用Illuminate \ Database \ Migrations \ Migration;使用Illuminate \ Database \ Schema \ Blueprint;

class CreateClientOrganisationTable扩展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]:找不到列:1054'where子句'中的未知列'clients.organisation_id'(SQL:select * from clients where clients.organisation_id为null)

现在我的理解是,我的数据库中不需要 clients.organisation_id 列,因为我有一个数据透视表,我做错了什么?我希望能够使用数据透视表获取我的所有组织及其客户 .

1 回答

  • 2

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

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

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

相关问题