Home > Back-end >  How make eloquent laravel relathionship migration with the same table?
How make eloquent laravel relathionship migration with the same table?

Time:02-23

if instead of having a users table where one user can follow many users. I would have a cows table where each cow has a single father and a single mother, where the parents can have many children. do I require an external table to store that or can I just add in my cows table the fields cow_father_id and cow_mother_id? -referring to making 2 eloquent relationships of cows table with same cows table and what this migration would look like?

CodePudding user response:

You could do this. I've tested as well.

Migration

Schema::create('cows', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->integer('father_id')->nullable();
    $table->integer('mother_id')->nullable();
    $table->timestamps();
});

Model

class Cow extends Model
{
    use HasFactory;

    public function father()
    {
        return $this->belongsTo(self::class, 'father_id');
    }

    public function mother()
    {
        return $this->belongsTo(self::class, 'mother_id');
    }

    public function children()
    {
        return $this->hasMany(self::class, 'father_id')->orWhere('mother_id', $this->id);
    }
}
  • Related