lundi 21 mars 2016

Laravel, check if data/record exists in any related table

Maybe someone will help me.

DB structure:

users
id, name

storage_items
id, name, user_id

archive_objects
id, name, user_id

In User model i have:

public function storageItem()
{
    return $this->hasOne(StorageItem::class);
}

public function archiveObject()
{
    return $this->hasOne(ArchiveObject::class);
}

I need check if data/record exists in any related table.

Something like this:

if (User::has('storageItem')->orHas('archiveObject')->find(1)->count()) {
    //exists
}

This works:

if (User::has('storageItem')->find(1)->count()) {
    //exists
}

and this too:

if (User::has('archiveObject')->find(1)->count()) {
    //exists
}

but that are two queries, i need one beautiful query :)

As a result, i need that when i click button "Delete user", before deleting, i check if data/record exists in any related table, if true, it will show warning message about deleting related data/record (from storage_items or archive_objects), else it will delete just user (from users).



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire