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

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();

Related

Get last record on GROUP BY using Laravel & MySql

I have two table (users and messages) .. I wrote a query to get all messages that users sent to me or I sent, using JOIN .. to get all the users I have contacted or they did.
as in the code below:
$users = Message::join('users', function ($join) {
$join->on('messages.sender_id', '=', 'users.id')
->orOn('messages.receiver_id', '=', 'users.id');
})
->where(function ($q) {
$q->where('messages.sender_id', Auth::user()->id)
->orWhere('messages.receiver_id', Auth::user()->id);
})
->orderBy('messages.created', 'desc')
->groupBy('users.id')
->paginate();
The problem here is when records grouped, I'm getting the old message not the new one according to its created_at .. So, I want to get the last record of the grouped records.
It seems like it would make more sense to make use of Eloquent's relationships here so that you can eager load the relationships instead of having to use join and group by:
$messages = Message::with('sender', 'receiver')
->where(function ($query) {
$query->where('sender_id', auth()->id())
->orWhere('receiver_id', auth()->id())
})
->orderByDesc('created') // is this meant to be 'created_at'?
->paginate();

How to order my query by most duplicates in Laravel?

On my website, users can post images.
Images can have tags.
There's 4 tables for this, the images table, the images_tag pivot table, the tag table, and of course the users table.
A user can have multiple images with the same tag(s).
I can pull up the tags a user has used across all his images with this query:
$userTags = Tag::whereHas('images', function($q) use($user) {
$q->where('created_by', $user->id);
})->get();
However, I want to make it so that I can order these tags based on how frequently a user uses them. In other words, I want to order by duplicates. Is this possible?
To achieve this, you're going to need to join the images_tags and images tables, count the number of tags, and order by those tags.
$tags = Tag::selectRaw('tags.*, COUNT(images.id) AS total')
->join('images_tags', 'tags.id', '=', 'images_tags.tag_id')
->join('images', 'images.id', '=', 'images_tags.image_id')
->where('images.created_by', $user->id)
->groupBy('tags.id')
->orderBy('total', 'desc')
->get();
The above query will only work in MySQL if the only_full_group_by option is disabled. Otherwise, you're going to need to either rewrite this to use a sub query, or do the ordering in the returned Laravel Collection. For example:
$tags = Tag::selectRaw('tags.*, COUNT(images.id) AS total')
->join('images_tags', 'tags.id', '=', 'images_tags.tag_id')
->join('images', 'images.id', '=', 'images_tags.image_id')
->where('images.created_by', $user->id)
->groupBy('tags.id')
->get();
$tags = $tags->sortByDesc(function ($tag) {
return $tag->total;
});
If you want to add this to your user model, per your comment, create a function similar to the following:
public function getMostUsedTags($limit = 3)
{
return Tag::selectRaw('tags.*, COUNT(images.id) AS total')
->join('images_tags', 'tags.id', '=', 'images_tags.tag_id')
->join('images', 'images.id', '=', 'images_tags.image_id')
->where('images.created_by', $this->id)
->groupBy('tags.id')
->orderBy('total', 'desc')
->limit($limit)
->get();
}

Laravel Eloquent model get unique user

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.

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();
});
}

Laravel 5 - compare query from one table to another query

I have two tables: a relationship table and a users table.
Relationship table looks like: 'user_one_id', 'user_two_id', 'status', 'action_user_id'.
Users table looks like: 'id', 'username'.
I would like to query the relationship table first and return an array of all the rows where the 'status' column = 0.
Then I would like to query the users table and return an array of ids and usernames where 'user_one_id' matches 'id'.
My code so far:
public function viewRequests()
{
$currentUser = JWTAuth::parseToken()->authenticate();
$friendRequests = DB::table('relationships')
->where('user_two_id', '=', $currentUser->id)
->where('status', '=', '0')
->get();
$requestWithUsername = DB::table('users')
->where('id', '=', $friendRequests->user_one_id)
->get();
return $requestWithUsername;
}
It's not working and I'm not sure what method is easiest to reach my desired output. How can I change these queries?
EDIT:
After reviewing the response, this is the working code:
$friendRequests = DB::table('users')
->select('users.id','users.username')
->join('relationships', 'relationships.user_one_id','=','users.id')
->where('relationships.status','=',0)
->where('relationships.user_two_id', '=', $currentUser->id)
->get();
Your SQL seems to be this:
SELECT id, username
FROM users
JOIN relationships
ON relationships.user_one_id = id
WHERE relationships.status = 0
Then the Laravel way:
DB::table('users')
->select('id','username')
->join('relationships', 'relationships.user_one_id','=','id')
->where('relationships.status','=',0)
->get();

Categories