2

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

1
  • you can use trigger from the backend to do that... Commented Mar 22, 2016 at 0:17

3 Answers 3

1

Try this:

User::where(function($query) { 
    $query->has('storageItem')
        ->orHas('archiveObject');
})->find(1);
Sign up to request clarification or add additional context in comments.

1 Comment

Woohoo, thank you dude, it works perfectly! And ir more better than my own solution :D $users = User::has('storageItem')->orHas('archiveObject')->get()->pluck('id')->toArray(); if (in_array(2, $users )) { //exists }
0

try this has and orWhereHas

eg:

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.