Globax
Globax

Reputation: 23

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).

Upvotes: 2

Views: 4961

Answers (3)

repkins
repkins

Reputation: 28

Try this:

User::where(function($query) { 
    $query->has('storageItem')
        ->orHas('archiveObject');
})->find(1);

Upvotes: 1

Globax
Globax

Reputation: 23

I had tried another code

User::whereHas('archiveObject', function() {})->orWhereHas('storageItem', function() {})->find(2)

but it is similar with this

User::has('archiveObject')->orHas('storageItem')->find(2)

i have this result

{
    "id": 1,
    "username": "admin",
    "created_at": "2016-02-05 11:45:12",
    "updated_at": "2016-03-20 15:12:15"
}

instead of this

{}

Result with "id": 1, i should have with this

User::has('archiveObject')->orHas('storageItem')->find(1)

Upvotes: 0

Qazi
Qazi

Reputation: 5135

try this has and orWhereHas

eg:

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

Upvotes: 0

Related Questions