首页 > 解决方案 > 一对多关系不起作用

问题描述

https://imgur.com/a/ob9rjIz 有两个表,一个称为 user,另一个称为 user_relation_user 我的关系是许多 user_relation_user 的用户,并且在我的迁移中。我想用 php artisan tinker 创建 10 个用户,所以我运行 factory(App\User::class, 10)->create(); 最后我访问我的数据库,所以从用户中选择 * 有 10 个用户,但在 user_relation_user 中不是 10 id 或者它是空的

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Administrator extends Model
    {

        protected $table = 'user_relation_user';
        protected $primaryKey  = 'id';
        protected $fillable = ['user_id'];


        public function users(){

            return $this->belongsTo(User::class,'user_id');
        }
    }



    <?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

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',
    ];

    public function administrator(){
        return $this->hasMany(Administrator::class,'user_id');
    }
}
//hasMany

我的迁移

<?php

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

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

            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('user_id_admin')->unsigned();
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

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

标签: phpdatabaselaravel

解决方案


你定义的关系是正确的,你只需要在用户模型中定义一个关系。

例子:

假设您正在开发一个博客系统,用户可以在其中发布博客。那么会有两个模型用户模型和博客模型

在用户模型中,您必须定义用户关系如下:

public function blogs()
{
   return $this->hasmany(Blog::class);
}

然后在博客模型中

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

推荐阅读