Php Laravel Collection-与Where具有等价关系的条件
我有三张桌子: 用户:Php Laravel Collection-与Where具有等价关系的条件,php,laravel,collections,Php,Laravel,Collections,我有三张桌子: 用户: Schema::create('users', function (Blueprint $table) { $table->unsignedInteger('id')->unique(); $table->string('name', 50)->nullable(); $table->timestamps(); }); 对话: Schema::create('conversations', function (Blu
Schema::create('users', function (Blueprint $table) {
$table->unsignedInteger('id')->unique();
$table->string('name', 50)->nullable();
$table->timestamps();
});
对话:
Schema::create('conversations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('token', 50)->nullable();
$table->timestamps();
});
和用户对话:
Schema::create('conversation_user', function (Blueprint $table) {
$table->unsignedInteger('conversation_id');
$table->unsignedInteger('user_id');
$table->dateTime('read_at')->nullable();
});
一个对话可以有两个用户
我为用户提供了这个类:
class User extends Model {
public function conversations(){
return $this->belongsToMany(Conversation::class, 'conversation_user', 'user_id', 'conversation_id');
}
public function getConversationWith($user_id){
return $this->conversations()->whereHas('users', function ($q) use ($user_id) {
$q->where('ml_users.user_id', $user_id);
})->first();
}
}
我的问题:我需要将getConversationWith()方法更改为:
public function getConversationWith($user_id){
return $this->conversations->where('users.user_id', $user_id)->first();
// Or this
return $this->conversations->whereIn('users.user_id', [$this->id, $user_id])->first();
}
获取与给定用户\u id的对话
有没有办法在收藏中做到这一点?
提前感谢您可以像下面那样完成这项工作,但如果您有一个大数据集,它将无法很好地执行
class User extends Model
{
public function conversations()
{
return $this->belongsToMany(Conversation::class, 'conversation_user', 'user_id', 'conversation_id');
}
public function getConversationWith($user_id)
{
// conversation IDs from target user
$conversationIds = Conversation::whereHas('user', function($query) use ($user_id)
{
$query->where('users.id', $user_id);
})->pluck('id')->toArray();
// all conversations from the current user where target user has participated
return $this->conversations()->whereIn('conversations.id', $conversationIds)->get();
}
}
希望有帮助