在我的查询中包含我的对话者的姓名(消息系统)

时间:2018-04-11 14:01:33

标签: laravel laravel-5 eloquent

我的网站上有一个消息系统(1v1),我想加入一些关于我的对话者(姓名,头像等)的信息。

我的结构不仅仅是常见的:

主题:

    Schema::create('threads', function (Blueprint $table) {
        $table->increments('id');            
        //...
    });

参加者:

    Schema::create('participants', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('thread_id')->unsigned();
        $table->integer('user_id')->unsigned();

        $table->foreign('thread_id')->references('id')->on('threads')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });

要获取我的主题我有这个查询:

    Thread::select(
        'users.name',
        'threads.id',
        //...
    )->join('participants', 'participants.id', '=', 'threads.id')
    ->join('users', 'users.id', '=', 'participants.user_id')
    ->where('participants.user_id', '=', $user->id)
    ->get();

当然,由于我的where条件,这是我的名字,而不是我的对话者的名字。我怎样才能加入对话者的信息并“排除”我的对话?

PS:请不要给我一个消息系统包。我想自己编写代码。

修改

模型中的关系线程:

public function users()
{
    return $this->belongsToMany('App\User', 'participants', 'thread_id', 'user_id');
}

public function participants()
{
    return $this->hasMany('App\Participant', 'thread_id', 'id');
}

编辑2:

@Jonas Staudenmeir代码:

$threads = Thread::select(
    'threads.id',
    'threads.last_sender',
    'threads.is_read',
    'threads.last_message',
    'threads.date'
    )->whereHas('users', function($query) use($user) {
    $query->where('users.id', $user->id);
})->with('users')->get();

foreach($threads as $thread) {
    $interlocutor = $thread->users->where('users.id', '!=', $user->id)->first();
}

尝试获取我只需要的字段:

$threads = Thread::select(
    'threads.id',
    'threads.last_sender',
    'threads.is_read',
    'threads.last_message',
    'threads.date'
    )->whereHas('users', function($query) use($user) {

    $query->select('users.id') // May be its gonna run faster
    ->where('users.id', $user->id);

})->with('users')->get();

foreach($threads as $thread) {
    $interlocutor = $thread->users->select(
        'id',
        'name',
        ...
    )->where('users.id', '!=', $user->id)->first();
}

$ intercolutor给我这个错误:Method Illuminate\Database\Eloquent\Collection::select does not exist.

1 个答案:

答案 0 :(得分:1)

试试这个:

$threads = Thread::select('id', 'last_sender', 'is_read', 'last_message', 'date')
    ->whereHas('users', function($query) use($user) {
        $query->where('users.id', $user->id);
    })
    ->with('users:users.id,name,avatar')
    ->get();

foreach($threads as $thread) {
    $interlocutor = $thread->users->where('id', '!=', $user->id)->first();
}