Laravel Eloquent model get unique user - php

I have this table, called "share":
and this is the "user" table:
So I get the list of shared item by "Share" model and the user associated with each entry:
class Share extends Model
{
public function UserDetail()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
}
What I need is to return the users with parent_id 3 :
$user = Share::where('parent_id', '=', 3)->paginate(15);
Its returns everything but I need to return just unique users like this:
Appreciate your help.

You can use groupBy method to get unique users. Refer this link
https://laravel.com/docs/5.4/queries
$user = Share::where('parent_id', '=', 3)->groupBy('item_id')->paginate(15);
Hopes answered your question.

According to your comments, you want to take all the shares with a similar parent_id (3):
$shares = Share::where('parent_id', 3)->get();
And their users. Each share belongs to a user. But each user user can share many times but want to take the user only once. We could do
//Using eloquent
$users = Share::where('parent_id', 3)
->join('users', 'users.id', '=', 'shares.user_id')
->select('users.id', 'users.email', 'users.first_name', 'users.last_name')
->groupBy('users.id', 'users.email', 'users.first_name', 'users.last_name')
->get();
//using Query builder
$users = DB::table('shares')
->join('users', 'users.id', '=', 'shares.user_id')
->where('shares.parent_id', 3)
->select('users.id', 'users.email', 'users.first_name', 'users.last_name')
->groupBy('users.id', 'users.email', 'users.first_name', 'users.last_name')
->get();
This should give you a distinct list of users having shared parent_id = 3.

Related

How can I separate out the Ids in tables joined within a Laravel Project

I have the following that joins together 3 tables, Images, Users, Profiles. The problem I have is that the result of the following only gives me 1 id field and that is the Id of the Profiles table. All 3 tables have their own Id fields.
Can I seperate it so that it is images.id, profiles.id and users.id?
$images = \App\Image::where('image_approved', '=' ,"feature_approved")
->join('users', 'users.id', '=', 'images.user_id')
->join('profiles', 'profiles.user_id', '=', 'images.user_id')
->get();
You can alias them like this:
$images = \App\Image::select([
'users.id as user_id',
'profiles.id as profile_id',
'images.id as image_id',
//... add the rest of the columns that you want to select here.
])
->where('image_approved', '=' ,"feature_approved")
->join('users', 'users.id', '=', 'images.user_id')
->join('profiles', 'profiles.user_id', '=', 'images.user_id')
->get();
or you can simplify it by using Eloquent relationships.
So in your Image model you would have:
public function user()
{
return $this->belongsTo(User::class);
}
public function profile()
{
return $this->hasOneThrough(Profile::class, User::class);
}
Then you can retrieve them:
$images = Image::with('user', 'profile')
->where('image_approved', '=' ,"feature_approved")
->get();
// now each $image in $images will have user and profile relationship
// $image->id
// $image->user->id
// $image->profile->id
Use alias in select like this:
->join('profiles', 'profiles.user_id', '=', 'images.user_id')
->select('images.*', 'users.*', 'profiles.*', 'images.id as imageID', 'profiles.id as profileId', 'users.id as usersId')
->get();

How can I retrieve row from another table in Laravel Eloquent?

I have 3 tables: posts, votes and users. I have written a neat code with Eloquent to retrieve just the posts where the user has not voted yet on.
$posts = Post::whereDoesntHave("votes")
->where('user_id', '=', $user_id)
->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
->take(20)
->get();
return response()->json(['posts' => $posts])->withCallback($request->input('callback'));
But also I want to retrieve user name from table users. I want to pass the data with json.
If I try to do it with query builder, it is hard to eliminate posts that have been voted already by the user.
You can do a join manually to the user table
$posts = Post::join('users', 'users.id', '=', 'posts.user_id')
->whereDoesntHave("votes")
->where('user_id', '=', $user_id)
->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
->take(20)
->get();
Or you could define a relationship in the Post model class.
public function user()
{
return $this->belongsTo('App\User');
}
Then you use with('user') to retrieve data from user table.
$posts = Post::with('user')
->whereDoesntHave("votes")
->where('user_id', '=', $user_id)
->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
->take(20)
->get();

Laravel Eloquent query get users from another model

I have another table called tableb and it has a user relationship defined through the user_id field.
I want to run a query against tableb where a certain date is within a certain range but then I want to grab the user table associated with that row but I only want it to grab the user if it's not been grabbed yet. I'm trying to do this all in 1 DB query. I have most of it done, but I'm having trouble with the unique part of it.
Here's what I have right now:
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->get();
So right now I have 3 entries in tableB from the same user, and ideally I'd like to only get 1 entry for that user.
How would I go about doing this?
Since you're selecting only users data, just add a groupBy clause in your query.
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->groupBy('users.id')
->get();
You should just add groupBy like this :
$tableB = TableB::select('users.*')
->join('users', 'tableb.user_id', '=', 'users.id')
->where('tableb.start_date', '>', date('Y-m-d'))
->groupBy('users.id')
->get
Try This Code
App/user.php
public function getrelation(){
return $this->hasMany('App\tableB', 'user_id');
}
In Your Controller
Controller.php
use App/user;
public funtion filterByDate(user $user)
{
$date = '2016-02-01';
$result = $user->WhereHas('getrelation', function ($query) use($date) {
$query->whereDate('tableb.start_date', '>', $date)
->first();
});
}

DISTINCT method using Laravel 5 eloquent query builder

I'm struggling to get unique results when using the DISTINCT method in laravel. This is my query
//Get users that are part of this sector
$users = DB::table('users')->distinct()
->join('projects', 'users.id', '=', 'projects.userID')
->where('projects.sectorID', '=', $sector->sectorID)
->get();
dd($users);
The result shows 3 users with the same ID, when I only want one of them in the results.
How should I change my query?
Try to use group by id
$users = DB::table('users')
->join('projects', 'users.id', '=', 'projects.userID')
->where('projects.sectorID', '=', $sector->sectorID)
->groupBy('users.id')
->get();
dd($users);

Laravel/Eloquent query going wrong

I have two tables, one with users, one with the name of their document. The first table consists of two columns: id and username. The second one consists of three columns: id, userid and document_name.
Now, I'm trying to create a query in the controller. What should happen, ideally, is that if someone visits website.com/{documentname}, it displays the username of the owner. Also, this should only happen if the current logged in user is the owner of the document. However, this is proving more difficult than I imagined. As in, I can't see what I'm doing wrong.
Here's the query:
$user = DB::table('documents')
->join('users', function($join)
{
$join->on('users.id', '=', 'documents.userid')
->where('documents.userid', '=', Auth::id())
->where('documents.document_name', '=', $document_name);
})
->get();
**Try this query :**
$user = DB::table('documents')
->leftJoin('users', 'users.id', '=', 'documents.userid')
->where('documents.userid', '=', Auth::id())
->where('documents.document_name', '=', $document_name);
->get();
$document_name isn't in scope for the join function: you need to pass it through to the closure via use
$user = DB::table('documents')
->join('users', function($join) use ($document_name)
{
$join->on('users.id', '=', 'documents.userid')
->where('documents.userid', '=', Auth::id())
->where('documents.document_name', '=', $document_name);
})
->get();
EDIT
Because the WHERE conditions apply to the base table, and not to the JOIN:
$user = DB::table('documents')
->join('users', function($join) {
$join->on('users.id', '=', 'documents.userid')
})
->where('userid', '=', Auth::id())
->where('document_name', '=', $document_name);
->get();

Categories