简体   繁体   中英

Relation one to many it doesn't work

https://imgur.com/a/ob9rjIz There are two tables one called user and another called user_relation_user My relation is an user to many user_relation_user and in my migration. I want to create 10 user with php artisan tinker so i run factory(App\\User::class, 10)->create(); at the end i access to my database so do select * from users there are 10 users but in user_relation_user isn't 10 id or it's empty

    <?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

My migration

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

The relation you define is correct,you just need to define a relation in user model as well.

Example:

Suppose you are developing a blog system where user can post blogs. then there will be two models user model and blog model

In User model you have to define user relation as below:

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

Then in blogs model

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM