cms
cms copied to clipboard
[5.x] Single relationship query builders
This PR is really intended to be an idea rather than a final implementation, the solution is a bit of a hack and a better approach is probably needed, but it would be really nice if this was possible.
At the moment if you're working in PHP and have an entry with either single or multi entries fields you can do this to fetch the published related entries:
$publishedChildren = $parent->children;
$publishedChild = $parent->child;
If you want related entries of any status you can do this with multi entries fields:
$anyChildren = $parent->children()->whereAnyStatus()->get();
But if you want a single related entry of any status there's not really a simple way to do it (I don't think). You can't do this with single entry fields, it throws a child method does not exist error:
$anyChild = $parent->child()->whereAnyStatus()->first();
When working with Eloquent models you can do $model->singleThing() with a belongs to relationship and it'll give you a query builder, it'd be great if Statamic could do the same.
This PR makes the above work by tricking any relationship fieldtypes into returning a query builder even if it's a single entry field. This only happens during __call so shouldn't affect anything else.
I think a better solution would be to do it in the fieldtype's augment method.
Agreed, much better idea, I will update.
You could have an option on the field.
Do you think it should be a field option or just a config option in statamic.system? I feel like if you want this behaviour you'd want it globally, it could be confusing if some fields behaved one way and some the other.
I feel like if you want this behaviour you'd want it globally
That's probably true
Closed in favour of https://github.com/statamic/cms/pull/11086.