Table filter with a relationship like so?

Well I know it fails with Call to a member function getRelated() on null, but thought maybe someone had some ideas. Trying to filter properties that belong to a particular project. Properties dont have a direct relationship to a project as you can see.
public function county(): BelongsTo
{
return $this->belongsTo(County::class, 'county_id');
}
public function projects(): ?BelongsToMany
{
if ($this->county) {
return $this->county->projects();
}

return null;
}
public function county(): BelongsTo
{
return $this->belongsTo(County::class, 'county_id');
}
public function projects(): ?BelongsToMany
{
if ($this->county) {
return $this->county->projects();
}

return null;
}
7 Replies
Dennis Koch
Dennis Koch2y ago
Shouldn’t this a be hasManyThrough?
Mark Chaney
Mark ChaneyOP2y ago
@Dennis Koch that possible without creating an additional table? Ah, i get what you would think that. I couldnt get a relationship to work on the Projects model for properties. I had to do an attribute like so:
public function getPropertiesAttribute()
{
$properties = collect();

$this->counties->each(function ($county) use (&$properties) {
$activeProperties = $county->properties->where('active', true);
$properties = $properties->merge($activeProperties);
});

return $properties;
}
public function getPropertiesAttribute()
{
$properties = collect();

$this->counties->each(function ($county) use (&$properties) {
$activeProperties = $county->properties->where('active', true);
$properties = $properties->merge($activeProperties);
});

return $properties;
}
Dan Harrin
Dan Harrin2y ago
you cant optionally return a relationship its not a real relationship then
Mark Chaney
Mark ChaneyOP2y ago
@Dan Harrin makes sense. Im assuming at this point I have to do a custom query builder instead to create such a filter
Dan Harrin
Dan Harrin2y ago
i wouldnt use a relationship, yeah. custom query() function
Mark Chaney
Mark ChaneyOP2y ago
ive changed a bit of my app since then, but unfortunately i had to stick with an attribute there
Dan Harrin
Dan Harrin2y ago
or, use county.projects as the relation name
Want results from more Discord servers?
Add your server