Here is my database table.
to_user_id is deleted in the users table that time total_like not should be 1
Here is my code
$user_id = 585;
$list = new self;
$list = $list->where('users.id', $user_id);
$list = $list->leftJoin('user_like_dislikes as total_like', function ($join) use ($user) {
$join->on('users.id', '=', 'total_like.to_user_id')
->where('total_like.like', 1);
});
$list = $list->select('users.*', \DB::raw('count(total_like.like) as total_like')
$list = $list->first();
Here are my user_like_dislikes data table
user_id
to_user_id
like
585
590
1
Here is my user table
id
deleted_at
590
Null
I above code to_user_id is not deleted in the user table so the output is total like is 1
But when I delete to_user_id in the users table that time output is total like 1 getting. this is wrong.
So, I want where I delete to_user_id in the users table that time total like should be 0
better way use relation to get solve this problem.
try bellow code :
in user model :
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
class User extends Model
{
protected $table = 'users';
public function likes(): HasMany
{
return $this->hasMany(Like::class, 'to_user_id', 'id');
}
}
the Like model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Like extends Model
{
protected $table = 'user_like_dislikes';
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
}
And Finally your query is:
$data = \App\Models\User::query()
->where('id',585)
->withCount('likes as likes_count') // for getting count of rows
->withSum('likes as likes_sum','like') // for getting sum of like column
->first();
$data->likes_count and $data->likes_sum your want value
and for handle soft delete you should use bellow tarit in user model
use \Illuminate\Database\Eloquent\SoftDeletes;
Related
I have a game where people can get some items and equip them.
The items data is placed in two tables that are in relationship.
Items table contains all the possible items and user_items table contains the items that are owned by a player.
user_items table: id | user_id | item_id | is_equipped
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
use HasFactory;
public function userItems()
{
return $this->belongsTo(UserItem::class);
}
}
items table: id | item_name | body_part
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserItem extends Model
{
use HasFactory;
public function items()
{
return $this->hasOne(Item::class, 'id', 'item_id');
}
}
Now I am getting a collection of the user's items
$userItems = UserItem::where('user_id', Auth::id())->get(),
How do I search this collection by related table's columns? For example I want to get user $userItems where is_equipped == 1 and body_part == "head".
What you need is filter by the relation like this:
$userItems = UserItem::where('user_id', Auth::id())->whereHas('items', function($q)
{
$q->where('is_equipped', '=', 1);
})->get();
You can use the Eloquent's relationships to search the collection by related table's columns.
To get the user's items where is_equipped == 1 and body_part == "head", you can use the following code:
$userItems = UserItem::where('user_id', Auth::id())
->whereHas('items', function ($query) {
$query->where('is_equipped', 1)->where('body_part', 'head');
})->get();
This code first queries the user_items table for all items that belong to the user. Then, it uses the whereHas method to filter the results based on the related items table's columns. The closure passed to whereHas receives a $query variable that is a instance of Query Builder that you can use to filter the items table.
You could also use the join method to join the items table to the user_items table and then filter by the columns in the items table:
$userItems = UserItem::join('items', 'items.id', '=', 'user_items.item_id')
->where('user_items.user_id', Auth::id())
->where('items.is_equipped', 1)
->where('items.body_part', 'head')
->get();
This will give you a collection of user_items that are owned by the user and have is_equipped = 1 and body_part = 'head' in the items table.
i want to create a query with multiple tables
the query that i need is:
SELECT orders.user_id, orderitem.product_id, orderitem.orderItem_quantity, product.product_price, product.product_imgPath,product.product_name
FROM orderitem, orders, product, users
WHERE orders.user_id = '$_Session[user_id]'
AND orderitem.product_id = product.product_id
AND orderitem.order_id = orders.order_id
AND orders.order_status = 1
and i try these codes:
1:
$cartProducts = DB::table('orderitem')
->join('product','product.product_id','=','orderitem.product_id')
->join('orders','orders.order_id','=','orderitem.order_id')
->where('orders.order_status','=','Waiting')
->where('orders.user_id','=',$userId)
->select('orderitem.*','orders.*','product.*','users.*')
->get();
The error that i get is:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'users'
2:
$cartProducts = DB::table('orderitem','orders','products','users')
->select('orderitem.*','orders.*','products.*','users.*')
->where('orders.user_id','=',$userId)
->where('orderitem.product_id','=','product.product_id')
->where('orderitem.order_id','=','orders_id')
->where('order_status','=','Waiting')
->get();
The error that i get is:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'orders'
And i know that i can't use multiple parameter for table function
Use laravel relationships https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
First, in your User model do:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function images()
{
return $this->hasMany('App\Images'); //make sure your images table has user_id column
}
}
And then in your Image table model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
Now in your controller:
$data = App\Post::user(1)->with('images');
return view('view_name', ["data" => $data]);
Your view:
#foreach($data->images as $image)
<img src="{{ $image->url }}">
#endforeach
I am using Laravel 5.4. I have 2 tables destination and user and a pivot table destination_user.
destination table
---|------
id | name
---|------
1 | sth
user table
---|------
id | name
---|------
1 | sth
and finally Pivot table
--------------|--------
destination_id| user_id
--------------|--------
1 | 1
2 | 1
3 | 2
I created a model for pivot table named destinationUser.
My destination model looks like this:
<?php
namespace App\models;
use App\Models\User;
use App\Models\DestinationUser;
use App\Models\DestinationImage;
use Illuminate\Database\Eloquent\Model;
class Destination extends Model
{
protected $table = 'destinations';
public function user() {
return $this->belongsToMany('App\Models\User');
}
public function destinationUser() {
return $this->hasMany('App\Models\DestinationUser');
}
}
I want to get all the destinations with their respective user detail using pivot table. I have tried so far is this:
$destinations = $this->destination->with('user', 'destinationUser')
->whereHas('destinationUser', function($query) {
$query->where('user_id', user()->id);})
->paginate(20);
dd($destinations[0]->destinationUser); gives me destination id and user id but I want user detail. How can I achieve this. Thank You for your help
You need a many to many relationship:
class Destination extends Model
{
protected $table = 'destinations';
public function destinationUser() {
return $this->belongsToMany('App\User');
}
}
controller
$destinations = $this->destination->with('destinationUser', function($query) {
$query->where('user.id', user()->id);})
->paginate(20);
As I was searching for faster execution of queries, there was a wrong design of tables. There is more load and time of execution for 3 table with pivot rather than 2 tables without pivot. So, I figured it out and corrected.
I have a table "transactions". in that table I have multiple columns which are id, user_id, customer_name, restaurant_name and time-stamps also.
What I need is if I have two or three same records in the table means restaurant_name is repeating with the same user_id. I need to get only unique records. If user ordered from same restaurant 3 times I need to get only 1 from those.
Example:
If I order form Pizza Hut 3 time and ordered from Subway 5 times. The result should contain 1 pizza hut and 1 subway.
Note: 1 user may have many transactions
Transaction Model:
<?php
namespace App;
use App\restaurant;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
public function restaurant(){
return $this->belongsTo(restaurant::class);
}
protected $fillable = [
'user_id','customer_name', 'restaurant_name' , 'ordered_items' ,
];
}
User Model:
<?php
namespace App;
use App\restaurant;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
public function restaurant(){
return $this->belongsTo(restaurant::class);
}
protected $fillable = [
'user_id','customer_name', 'restaurant_name' , 'ordered_items' ,
];
}
I am trying to getting desired results like this but It is showing me an error:
BadMethodCallException in Macroable.php line 74:
Method distinct does not exist.
$user->transactions->distinct("restaurant_name");
distinct is not an existing function for Laravel collections, but unique is.
$user->transactions->unique("restaurant_name");
However that will query all transactions and filter in code. To get the distinct rows using a query, you could do the following:
$user->transactions()->groupBy('restaurant_name')->get();
I have a database running with username, password and user_id as primary key
and I'm trying to get the highest number out of the user_id column using eloquent.
This is my current error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.id' in 'where clause' (SQL: select * from users where users.id = 2 limit 1)
This is what my model looks like:
users.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
use Eloquent;
class users extends Eloquent
{
public static function register()
{
$user_id = users::find(DB::table('users')->max('user_id'));
return $user_id;
}
}
Usually, Laravel considers the primary key name is id. You must declare your primary key name if it's not id. So, add this in your user class:
protected $primaryKey = 'user_id';
Here is how the whole class should look:
class users extends Eloquent
{
protected $primaryKey = 'user_id';
public static function register()
{
$user_id = users::find(DB::table('users')->max('user_id'));
return $user_id;
}
}
Get the highest user like this
$user = users::orderBy('user_id', 'desc')->first();