Mysql
 SQL >> Base de Dados >  >> RDS >> Mysql

Escrevendo os Relacionamentos Corretos do Laravel Eloquent

Para usar o Eloquent de forma eficaz, você primeiro precisa definir seus relacionamentos. Uma mensagem pertence tanto a um thread quanto a um usuário. Veja como fazer dentro do model Message:

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

Para o inverso, dentro do model User:

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

E dentro do model Thread:

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

Agora, no seu controller, você pode fazer:

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

Isso lhe dá todos os threads que pertencem ao usuário atualmente logado. Não tenho total certeza de ter entendido a pergunta, então fique à vontade para perguntar. Editar: você poderia verificar a propriedade assim:

$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 } 

Alternativa mais idiomática, aproveitando os relacionamentos: $isCurrentUserThread = Auth::user()->threads()->where('id', $id)->exists();