This is my model
class ModelA extends Model
{
use HasFactory;
public function model_b()
{
return $this->hasMany(ModelB::class);
}
}
This query works well.
$lastWeek = ModelA::find(1)
->model_b->get();
When I am using where clause query
$lastWeek = ModelA::where('name','=',$name)
->model_b->get();
It says:
Property [model_b] does not exist on the Eloquent builder instance.
CodePudding user response:
In your first query, find()
returns the model, so you are able to access the relation. I think the ->get()
in that instance doesn't do anything.
In your last query, the where
clause doesn't return the model (its returning the eloquent builder) before you try and access its relation. You could use firstWhere()
, so that it would be
$lastWeek = ModelA::firstWhere('name', $name)
->model_b;
CodePudding user response:
You can do like this.
$lastWeek = ModelA::where('name','=',$name)
->with('model_b')
->get();
$lastWeek = $lastWeek->model_b;