如何在Laravel Migration中创建联接表?

时间:2019-10-15 03:43:45

标签: laravel join eloquent migration

我有一个用户表,其中以下各列与用户模型与电话模型具有一对多关系。

create_users_table.php

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

然后我有一个电话表,该表的外键为user_id create_phones_table.php

public function up()
{
    Schema::create('phones', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('user_id')->unsigned();
        $table->string('phone');
        $table->timestamps();

        $table->foreign('user_id')
        ->references('id')
        ->on('users')
        ->onDelete('cascade');
    });
}

我的用户模型

<?php

namespace App;

use App\Phone;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Define Relationship
     */

    public function phones()
    {
        return $this->hasMany(Phone::class);
    }
}

我的手机型号

<?php

    namespace App;

    use App\User;
    use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    protected $table = 'phones';
    protected $fillable = ['phone' , 'user_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

我想在数据库调用phone_user_table.php中有第三个表。类似于数据透视表,其中我已加入用户表和电话表,可以在其中查看所有记录。这是我尝试连接表的代码。

create_phone_user.php

<?php

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

class CreatePhoneUser extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('phone_user', function (Blueprint $table) {

            $table->unsignedBigInteger('user_id')->unsigned();
            $table->unsignedBigInteger('phone_id')->unsigned();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('phone_id')->references('id')->on('phones')->onDelete('cascade');

            $table->timestamps();

            $table 
            ->join('users', 'users.id', '=', 'phone_user.user_id')
            ->join('phones', 'phones.id', '=', 'phone_user.phone_id')
            ->select('phone_user.*', 'users.name', 'phones.phone')
            ->get();
        });
    }

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

但是,似乎正在提供基本表电话。

感谢所有提供的帮助。

谢谢。

1 个答案:

答案 0 :(得分:0)

这是基于Laravel Many to Many Relationship Docs.

的工作方式

第一

您需要创建2个您想建立关系的model

  

在您的示例中,您具有 USER PHONE 关系。

在您的用户模型中,您需要这样声明关系:

public function phones() {
  return $this->belongsToMany(Phone::Class);
}

在您的手机型号中,您可以这样操作:

public function users() {
  return $this->belongsToMany(User::Class);
}

第二

您需要有3个migration,一个分别代表userphonephone_user。所以应该看起来像这样。

电话用户迁移

Schema::create('phone_user', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->unsignedBigInteger('phone_id')->index();
  $table->unsignedBigInteger('user_id')->index();
  $table->timestamps();

  $table->foreign('phone_id')->references('id')->on('phones')->onDelete('cascade');
  $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
  

注意:userphone migration中都不需要具有unsignedBigInteger。

现在有了user listphone list时,您可以像这样将phone分配给user

控制器

$user = User::find(1);
$phone = Phone::find(1);

$user->phones()->attach($phone);