Laravel雄辩地加入了三张桌子

时间:2020-07-04 21:47:37

标签: laravel

我开始研究一个小的Laravel项目,我想加入三个表来获得客户组织,因为一个客户可以在多个组织中。

我有三个表:usersorganizationsclient_organizations

例如,我如何使用雄辩的话机获得用户ID等于1的客户组织:

这是我的表结构:

组织表:

public function up()
{
    Schema::create('organizations', function (Blueprint $table) {
        $table->bigIncrements('id');

        $table->string('organization_name');
        $table->string('phone');
        $table->string('fax');
        $table->string('address');
        $table->string('city');
        $table->string('zipcode');
        $table->string('website');
        $table->string('linkedin');
        $table->string('facebook');
        $table->string('twitter');
        $table->timestamps();

    });
}

客户组织:

public function up()
{
    Schema::create('client_organizations', function (Blueprint $table) {
        $table->bigIncrements('id');

        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');



        $table->bigInteger('organization_id')->unsigned();
        $table->foreign('organization_id')->references('id')->on('organizations');
        
        $table->timestamps();
    });
}

NB:另外,我还有Laravel Auth随附的 Users 表。

1 个答案:

答案 0 :(得分:0)

当您有一个用于案件的数据透视表时,您不需要三张桌子。

return DB::table('client_organizations')
    ->join('organizations', 'organizations.id', '=', 'organization_id')
    ->where('user_id', 1)
    ->get([
        'organizations.*'
    ]);

您可以将DB::table('client_organizations')替换为client_organizations表的模型名称。

相关问题