2016-05-31 87 views
1

我对laravel和口才很新。Laravel雄辩的查询权数据

我有2个表threadsmessages你可以在下面的链接查看结构:

线程

threads

消息

messages

现在我的目标是只查询具有该表的线程中的线程消息表中与登录用户相同的user_id。

有没有办法通过雄辩做到这一点,或者我必须为此编写一个查询?

我目前得到的所有线程是这样的:

$thread = Thread::findOrFail($id); 

但是这给安全问题,因为你可以,如果你在我的路线改变ID去任何线程。

编辑

我的当前显示功能:

public function show($id) 
    { 
     $currentUserId = Auth::user()->id; 
     $threads = Thread::forUser($currentUserId)->latest('updated_at')->get(); 

     try { 
      $thread = Thread::findOrFail($id); 
     } catch (ModelNotFoundException $e) { 
      Session::flash('error_message', 'Oops, not found.'); 
      return redirect('messages'); 
     } 


     if(array_has($threads, $thread)){ 
      $users = User::whereNotIn('id', $thread->participantsUserIds($currentUserId))->get(); 
      $thread->markAsRead($currentUserId); 
      return view('messenger.show', compact('thread', 'users')); 
     }else{ 
      Session::flash('error_message', 'Oops, not found.'); 
      return redirect('messages'); 
     } 

    } 

我需要一种方法来检查,如果$线程是在$线程。

+0

你是什么意思的线程做? – Codearts

+0

在一个线程中可以有多条消息。例如,我创建了一个线程“discussion1”,在这个讨论中可以有多个消息。线程就像2个用户之间的dm。 – Cruzito

+0

@Codearts我希望这是有道理的,我想说:) – Cruzito

回答

3

如果你想用雄辩必须先定义的关系。 一条消息属于一个线程和一个用户。下面是如何定义的关系: 内部消息模型:

public function user() 
{ 
    return $this->belongsTo('App/User'); //User model 
} 

public function thread() 
{ 
    return $this->belongsTo('App/Thread'); //Thread model 
} 

要定义你做以下逆: 内部用户模式:

public function threads() 
{ 
    return $this->hasMany('App/Thread'); 
} 

里面的线程模型:

public function messages() 
{ 
    return $this->hasMany('App/Message'); 
} 

现在您可以在您的控制器中执行以下操作:

$threads = Auth::user()->threads; 

现在你在当前登录的用户拥有的所有线程。 我不知道我是否有这个问题,所以要求离开。

编辑: 你可以检查就像这样:

$thread = Thread::find($id); 
$isCurrentUserThread = false; 
foreach(Auth::user()->threads as $currentUserThread) { 
    if($currentUserThread->id == $thread->id) { 
     $isCurrentUserThread = true; 
     //$thread belongs to the current user 
    } 
} 

if($isCurrentUserThread) { 
    //the thread belongs to the current user 
} else { 
    //it doesn't belong to the current user 
} 
+0

的事情是,我没有任何的模型,因为我用这个包:https://github.com/cmgmyr/laravel-messenger,但我发现他们使用'$线程函数=主题:: forUser($ currentUserId) - > latest('updated_at') - > get();'这个例子。现在我是想检查是否是querried与路由的ID阵列处于数组$线 – Cruzito

+0

我已经与我的功能更新OP检查出来,如果你想 – Cruzito

+0

那么你得到了什么错误? – Codearts

1

有一个方法调用来获取当前用户的ID:

$logged_in_user = Auth::user()->id 

只要确保在顶部的地方包括此部分:

use Illuminate\Support\Facades\Auth; 

然后,你可以只得到所有消息其中user_id等于登录用户...

$messages = App\Message::where('user_id', '=', $logged_in_user)->get(); 
// the get() method will get all messages, not just one 

从那里,你可以提取$ m essages变量,并抓住​​所有的thread_ids,然后,你可以使用find方法的线程模型,如下所示:

$threads = App\Thread::find([1, 2, 3, 4, ...]);