Home > OS >  laravel eloquent relationship for indirectly related model
laravel eloquent relationship for indirectly related model

Time:12-21

I want a relationship where two unrelated models are linked together with a linker model.

My tables are like:

card table

id(pk)
name

User table

id(pk)
username
password
card_id(fk)

Feature table

id(pk)
name
card_id(fk)

How can i define an eloquent relationship to access all the features of user's card from user model like this:

class User extends Model
{
    use HasFactory;
    public function features(){
        return $this->relatonship_statement;
    }
}

and when I tried in Card Model:

class Card extends Model
{
    use HasFactory;
    public function features(){
        return $this->hasMany(Feature::class);
    }
}

and in User model:

class User extends Model
{
    use HasFactory;

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

I get error:

App\Models\User::features must return a relationship instance.

CodePudding user response:

What you really want is an accessor function, not a relationship. This is how you would do to achieve what you want.

class User extends Model
{
    use HasFactory;

    protected $appends = ['features']; //to append features in the response json

    public function card(){
        return $this->belongsTo(Card::class); //editted User to Card
    }
    public function getFeatures(){ //accessor method
        return $this->card->features()->get();
    }
}

sample result after returning user in a controller function

return User::query()->with('card')->first();

enter image description here

However, the right way is to access the features through the Card Relationship because these two models have a direct relationship.

  • Related