Mysql
 sql >> Database >  >> RDS >> Mysql

Laravel eloquente interrogare i dati giusti

Se vuoi usare eloquent devi prima definire una relazione. Un messaggio appartiene a un thread e a un utente. Ecco come definire le relazioni:All'interno del modello del messaggio:

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

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

Per definire l'inverso, procedi come segue:Modello utente interno:

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

All'interno del modello Thread:

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

Ora puoi fare quanto segue nel tuo controller:

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

Ora hai tutti i thread dell'utente attualmente connesso. Non sono sicuro di aver risposto correttamente alla domanda, quindi chiedi pure.

Modifica:puoi controllare in questo modo:

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