Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

How about...

class StoreMember extends Model
{
    public function visits()
    {
        return $this->hasMany('Visits', 'user_id', 'user_id')
            ->where('store_id', $this->store_id);
    }
Last updated 8 years ago.
0

Hey @Neoglyph, thanks for the reply. Unfortunately I don't think this works when eager loading the relationship. With the proposed method, if you lazy load like this it works:

$storeMember = StoreMember::where('user_id',1)->where('store_id',1)->first();
dd($storeMember->visits);

However, if you eager load like this it doesn't work:

$storeMember = StoreMember::with('visits')->where('user_id',1)->where('store_id',1)->first();
dd($storeMember->visits);

I think its because at the time the relationship is processed $this->store_id is null when eager loading. It seems like there should be a way to define multiple indexes for the relationship, not just one. Taylor seems pretty opposed to supporting composite keys for some reason. I'll just stick with my single primary key for the time being I guess. Thanks again.

0

Use Compoships to add support for multi-columns relationship in Laravel 5's Eloquent: https://github.com/topclaudy/compoships

0

Sign in to participate in this thread!

Eventy

Your banner here too?

luoshiben luoshiben Joined 30 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.