Laravel Request Relationships on One Model Instance

I know that I can use count()“Sensitivity” in Laravel to query relationships, for example:

if(count($question->answers()))

Where answers()is the relation hasMany:

 public function answers()
    {
        return $this->hasMany('App\Models\Answer', 'question_id');
    }

My question is: how can I do this when $question- this is not a whole collection, but one instance of the model?

$question = Question::where('id',$key)->first(); 

How to request the above question and only this question for potential communication using count()?

I always get count()more than zero, even if the selected question has no related answers, which means that my if-block always works and returns unjustified values null:

if(count($question->answers()))
   {
   //returns nulls
   }
+4
source share
2

$question->answers() QueryBuilder, count(), , , 1. $question->answers ( property, a method) $question->answers()->get();, Collection, count() :

$question = Question::where('id',$key)->first();

if(count($question->answers) > 0){
  // Do something
}

// OR

if(count($question->answers()->get()) > 0){ 
  ... 
}

@maraboc, $question answers ->with():

$question = Question::with(["answers"])->where('id',$key)->first();

$question->answers() QueryBuilder, property count().

+2

, count($question->answers()) , $question->answers() - Relation, , , , $question->answers.

, :

  • : count($question->answers)
  • : $question->answers()->count()

0

Source: https://habr.com/ru/post/1680974/


All Articles