简体   繁体   中英

Laravel Relationship with condtion on foreign key (toggle foreign key on relation)

For a small chat purpose, I am using below relationship Model

class Chat extends Model
{
    protected $table = 'chats';
    protected $primaryKey = 'chat_id';
    protected $filllable = [
        'chat_id',
        'sender_id',
        'reciever_id',
        'content',
        'sender_type',
        'reciever_type',
        'view_status'
    ];
class Admin extends Authenticatable
{
    public function chats()
    {
        return $this->hasMany(Chat::class, 'sender_id', 'admin_id');
    }
}

but the issue is both user's are in the same table some times it is sender_id sometimes it is reciever_id so I want to return the above relationship with the condition (if the receiver type in chat table is 1 it should be reciever_id else it should be the sender_id)

Controller

    $seller_id = auth()->guard('seller')->user()->seller_id;

    $chatLists = Admin::whereHas('chats', function ($q) {
        $q->where('reciever_type', 2); 
        $q->orWhere('sender_type', 2);       
    })
    ->with(['chats' => function ($q) {
        $q->where('reciever_type', 2);
        $q->orWhere('sender_type', 2);
    }])
    ->orderBy('created_at', 'desc')
    ->get();
      
    return view('seller.chat.index', compact('chatLists'));
}

sender_type and receiver_type don't seem to do much.

If you retrieve $seller_id and intend to get all chats from $seller_id ,
both chats with $seller_id as sender
and chats with $seller_id as receiver

Then your query could look like this.

$seller_id = auth()->guard('seller')->user()->seller_id;

$chatLists = Admin::whereHas('chats', function ($q) use ($seller_id) {
    $q->where('receiver_id', $seller_id)
        ->orWhere('sender_id', $seller_id);       
})
->with(['chats' => function ($q) use ($seller_id) {
    $q->where('receiver_id', $seller_id)
        ->orWhere('sender_id', $seller_id);
}])
->latest()
->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM