【问题标题】:How do I create A joined table in Laravel Migration?如何在 Laravel 迁移中创建连接表?
【发布时间】:2019-10-15 13:23:08
【问题描述】:

我有一个包含以下列的用户表,其中用户模型与手机模型具有一对多关系。

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

但是,它似乎给 Base Table 电话已经存在。

感谢所有提供的帮助。

谢谢。

【问题讨论】:

  • 确认您的迁移已成功完成?
  • Laravel 迁移使用连接,所以请使用“数据透视表”。关注此链接easylaravelbook.com/blog/…
  • 你想通过在Blueprint 对象上调用join 来做什么?
  • 一个电话可以属于一个用户,并且用户有多个电话号码。 usersphones 表足以满足您的需要。为什么你需要一个数据透视表??
  • 您可以稍后在查询时加入两个表。在模式中,您不能只加入它们并在此处进行查询。这有意义吗??

标签: laravel join eloquent migration


【解决方案1】:

这是基于Laravel Many to Many Relationship Docs.的工作原理

第一

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

在您的示例中,您有 USERPHONE 关系。

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

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);

【讨论】:

    猜你喜欢
    • 2016-06-09
    • 2015-12-21
    • 2013-07-19
    • 2013-09-26
    • 2017-07-02
    • 2015-01-14
    • 2021-10-06
    • 2011-12-02
    • 2015-03-28
    相关资源
    最近更新 更多