PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 28, 2022

[FIXED] How make eloquent laravel relathionship migration with the same table?

 February 28, 2022     database, eloquent, laravel, migration, relationship     No comments   

Issue

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?


Solution

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


Answered By - sithuaung
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing