octobercms / october

Self-hosted CMS platform based on the Laravel PHP Framework.
https://octobercms.com/
Other
11.01k stars 2.21k forks source link

AttachOne relation breaks if parent select doesn't include id field #2944

Closed bombozama closed 7 years ago

bombozama commented 7 years ago

I've set up a model to use a picture.

public $attachOne = [
        'picture' => 'System\Models\File'
    ];

I've properly loaded a picture using the relation. The picture is in the filesystem and correctly refered to in the system_files table.

When querying for models, the following should retrieve the model and eagerload the picture

$model = MyModel::select('field1', 'field2', ..., 'fieldn')
        ->with('picture')
        ->first();

Attempting to get picture path with:

$model->picture->getPath();

Getting Exception: Call to a member function getPath() on null (instead of the picture path)

After a lot of struggling, I managed to figure out that since the id field was not included in the select statement, the query that fetches the picture from the system_files table fails to relate both models:

select * from `system_files` where `system_files`.`attachment_type` = 'Acme\Plugin\Models\MyModel' 
and `system_files`.`attachment_id` is null and `field` = 'picture' and 
`system_files`.`attachment_id` is not null order by `sort_order` asc limit 1

Note the

`system_files`.`attachment_id` is null

instead of

`system_files`.`attachment_id` = 'model-id'

I don't know if it is a bug or the expected behavior, but I would like to simply point out that one should be careful to include the id field (whatever it's called in your system) in order to ensure that the relation works.

Hope it helps!

LukeTowers commented 7 years ago

Documented in https://github.com/octobercms/docs/commit/c47ca9d879a405d2b5db8201b22a54df600b1333, thanks for the report!