Laravel 7 One To Many Relations?

Viewed 466

Below are all of the models, migrations and controller.

Donation Model

class Donation extends Model
{
    protected $guarded =[];

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

    public function items(){
        return $this->belongsTo(DonationItems::class);
    }
}

Donation Items Model:

class DonationItems extends Model
{
    protected $guarded=[];

    public function donation(){
        return $this->hasMany(Donaition::class);
    }
}

Donation Items Migration:

public function up()
{
    Schema::create('donation_items', function (Blueprint $table) {
        $table->id();
        $table->string('category');
        $table->timestamps();
    });
}

Donation Migration:

public function up()
{
    Schema::create('donations', function (Blueprint $table) {
        $table->id();
        $table->string('item');
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('donation_item_id');
        $table->timestamps();
    });
}

In my controller I want to access the items as follows:

$don = Donation::all();
$don->items;

But I'm unable to achieve this.

1 Answers

Its not working because laravel follows one rule for relationships:

Remember, Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.

So you can try by supplying local and foreign id

So it would look something like this

Donation Model class Donation extends Model { protected $guarded =[];

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

    public function items(){
        return $this->belongsTo(DonationItems::class, 'donation_item_id', 'id');
    }
} 

Donation Items Model:

class DonationItems extends Model
{
    protected $guarded=[];

    public function donation(){
        return $this->hasMany(DonationItems::class, 'id', 'donation_item_id');
    }
}

I am writing from my head you might need to swap local and foreign ID's

Related