admin管理员组

文章数量:1281055

I have this table structure in linked_accounts table. user_id and linked_user_id is attached with users table.

when any user link an account, we store it in linked_accounts table. user_id is considered as main account. Now in Laravel eloquent I need to return all linked_accounts of a logged in user in an API.

So it would be simple when main user is logged in. But if I'm logged in with user_2 or user_3 how can I fetch other user's ids?

If any changes needed in table structure please let me know.

I have this table structure in linked_accounts table. user_id and linked_user_id is attached with users table.

when any user link an account, we store it in linked_accounts table. user_id is considered as main account. Now in Laravel eloquent I need to return all linked_accounts of a logged in user in an API.

So it would be simple when main user is logged in. But if I'm logged in with user_2 or user_3 how can I fetch other user's ids?

If any changes needed in table structure please let me know.

Share Improve this question asked Jan 24 at 9:42 Darshan SoniDarshan Soni 311 silver badge10 bronze badges 2
  • 1 Add field main_user_id to users and things will be simple. – Maksim Commented Jan 24 at 10:14
  • 1 can you show an example of what you want to do and what issue you have exactly? Why is user_2 or user_3 more complicated that user_1? – kris gjika Commented Jan 24 at 15:00
Add a comment  | 

1 Answer 1

Reset to default 0

There are multiple ways to go about this. With the way you have gone about it, what you could do is this;

public function linkedAccounts(): BelongsToMany
{
    return $this->belongsToMany(
        User::class,
        'linked_accounts',
        'user_id',
        'linked_user_id'
    );
}

public function linkedByAccounts(): BelongsToMany
{
    return $this->belongsToMany(
        User::class,
        'linked_accounts',
        'linked_user_id',
        'user_id'
    );
}

public function allLinkedAccounts(): Collection
{
    return $this->linkedAccounts->merge($this->linkedByAccounts);
}

Another way is to do it bi-directionally, which means you'll have to always write two records; that is if you persist ID 1 as user_id and ID 2 as linked_user_id, you'll do it the other way round as well. 2 as user_id and 1 as linked_user_id. This way you can avoid complex queries if you ever need to do some extra computation, all you have to worry about is one relationship.

public function linkedAccounts(): BelongsToMany
{
    return $this->belongsToMany(
        User::class,
        'linked_accounts',
        'user_id',
        'linked_user_id'
    );
}

BTW, you can apply this same reasoning for the relationship as HasMany.

本文标签: eloquent relationshipFetch all linked accounts in LaravelStack Overflow