lundi 8 octobre 2018

best way to get modified relationship laravel

we have these Models : Question and Answer.
in the answers table, we have a boolean column with the name acceptedand we have just 1 accepted Answer.
We want to get Question with Its Answers and accept answer separately.
I use 2 approaches but I don't know which is better:
1- check if the relation is loaded if loaded filter relations and get accepted answer like this:

if(!$this->relationLoaded('answers')){
            $this->load('answers');
        }
        return $this->answers->firstWhere('accepted',true);

2- we can use this approaches too:

function accepted_answer(){
  return $this->answer()->where('accepted',true);
}

the problem of the second approach is we get an array but we expect a single response or null. Is there any better approach for this or we can use neither 1 or 2?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire