0

I got this query:

$users = DB::table('users')->whereExists(function($query)
        {
            $query->select(DB::raw(1))
               ->from('galleries')
               ->whereRaw('galleries.user_id = users.id');
        })->get();

This query selects all users who have gallery. Problem is that I can't use eloquent releationships now. Whenever i try to loop like this:

@foreach ($user->gallery as $gallery)
    {{$gallery->name}}      
@endforeach 

I get error:

Undefined property: stdClass::$gallery

It happens with all other tables. What am I doing wrong here? My realationships are defined and they work just fine, i got problems only in this query. Thanks.

EDIT
Since it's not eloquent query, could you show me example how to write query, into few tables with eloquent. For example, I need all users who have their status approved in example table

5
  • 2
    You're not selecting from the User model, you're selecting from DB::table('users'). Commented Jun 30, 2015 at 10:19
  • 1
    You're not using eloquent here, you're using fluent, 2 different things. If users and galeries are in a relation, you shouldn't need to do this to being with. Commented Jun 30, 2015 at 10:20
  • Thanks. So could you show me an example how do i write eloquent query for 2 tables? Since I need only those users, who have gallery? It's just example, in real time project I have to pick all users, where galleries have status approved. Commented Jun 30, 2015 at 10:25
  • post your User and Gallery model code please Commented Jun 30, 2015 at 11:05
  • I manage to do it by myself. I used User:: instead of DB::table('users'). Thanks for help. Commented Jun 30, 2015 at 11:39

1 Answer 1

3

First, determine a relationship in the User class, like this:

class User {
    // Determine relation to Example table
    public function examples() {
        return $this->hasMany('Example', 'user_id', 'id'); // second parameter is the foreign key
    }
}

Then the query:

User::whereHas('examples', function( $query ) {
    $query->where('status','approved');
})->get();
Sign up to request clarification or add additional context in comments.

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.