I have two tables employees and customers , i've gave the schema below.
Customers('id' , 'username', 'location');
Employees('id' , 'EmployeeID' , 'CustomerID', 'location');
Currently I can use a query to retrieve customers details like the below query , note this is when the user is logged into the system hence the Auth::
$customerQuery1 = DB::table('customer')
->where('id', '!=', Auth::id())
->where('item', '=' , Auth::customer()->recommendation)
->get();
Each Employee has many customers ,I want other customers to see other customer items so i have attach the CustomerID field which is a foreign key and relates to the id field within the Customer table.
I've tried something like the below however I think I may need a join query but i'm unsure.
$query2 = DB::table('Customer','Employee')
->select('username')
->where(['EmployeeID' => Auth::id(), 'CustomerID' => 'id'])
->get();
$query2 = DB::table('Customer')
->select('username')
->join('Employee', 'Customer.id', '=', 'Employee.CustomerID')
->where(['EmployeeID' => Auth::id(), 'CustomerID' => 'id'])
->get();
I am then returning the values to my blade file like the below
return view ('pages.dashboard')
->with('query1',$query1)
and then Im using php indentation within my blade file to return the users data
#foreach ($query1 as $Userfound)
{{ $Userfound->username}}</p>
#endforeach
Actual Query needed in plain english
so I need to select a customer , where CustomerID == id
NOTE: id is from the customers table, CustomerID stored in the Employees table.
You can create Models using Laravel, for example:
Employee.php
public function customers()
{
return $this->hasMany('App\Customer');
}
Customer.php
public function employee()
{
return $this->belongsTo('App\Employee');
}
Which you can access like so:
$customer = Customer::where('id',Auth::user()->id)->firstOrFail();
or
$employee = Employee::where('id',Auth::user()->id)->firstOrFail();
And to see an employee's customers:
$employee->customers()->get();
Or to see the other customers of $customer's employer:
$customer->employee()->customers()->get();
Related
I have User and UserComplains Models.
I like to retrieve users that have UserComplains more than 2 times in the last 24 hours.
users:
id
user_complains:
complained_id ->ref-> users.id
created_at
this is what I tried and it is working:
$users = User::select('users.*')->join('user_complains' , 'users.id' , '=' , 'user_complains.complained_id')
->whereRaw("(
select count(*) from `user_complains`
where `user_complains`.`complained_id` = `users`.`id`
and `user_complains`.`created_at` > ?) >= ?" , [now()->subHours(24), 2])
->groupBy("users.id")
->get();
the above code is fine and is working, but I wonder is there a better way to do that?!
For something like this you can use whereHas(). :
$users = User::whereHas('*relationship*', function ($query) {
$query->where('created_at', '>=', now()->subDay(1));
}, '>', 2)->get();
As mentioned in the documentation, you can pass additional checks as the 3rd and 4th param so in this case you want to say where the user has more that 2 user_complains.
NB You will need to replace *relationship* with the actual name of the relationship.
You can do the following:
User::whereHas('complaints', function($query) {
$query->where('created_at', '>=', '2020-04-26');
}, '>', 2)->get();
In order for this to work though you need to have set up a relationship between your User and UserComplaint models.
class User extends Model
{
public function complaints()
{
return $this->hasMany(UserComplaint:class);
}
}
I have a table with the name "reportable" and want to display the entries in a table on the website. Unfortunately I can't get the database query right, I don't have much experience with a One To Many (Polymorphic) table.
databse table:
Schema::create('reportable', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned()->nullable()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
$table->integer('reason');
$table->integer('reportable_id')->index();
$table->string('reportable_type')->index();
$table->text('notice')->nullable();
$table->tinyInteger('status')->default(0)->index();
$table->timestamps();
});
In the table on the web page I want to display only entries with the same reportable_id and reportable_type only once.
In addition, the entries with the same reportable_id and reportable_type should be counted and displayed as a numerical value.
In addition, the entries in the column 'reason' with the same reportable_id and reportable_type should be counted and displayed with the respective entry and as a numerical value.
if you want a list:
$query = Report::select(\DB::raw('reportable.reportable_id,reportable.reportable_type,SUM(reason) as reason_total')) // Or \DB::raw('reportable.*,SUM(reason) as reason_total')
->groupBy('reportable_type')
->groupBy('reportable_id')
->get();
And if you want to have a specific row you should have your query like this:
$reportableId = 1; // $reportableId = Input::get('report_id'); // It can come from get parameters http://localhost/reports?report_id= 1
$reportableType = 'User';
$query = Report::select(\DB::raw('reportable.reportable_id,reportable.reportable_type,SUM(reason) as reason_total')) // Or \DB::raw('reportable.*,SUM(reason) as reason_total')
->groupBy('reportable_type')
->groupBy('reportable_id')
->get();
if($reportableId)
$query = $query->where('reportable_id' , $reportableId );
if($reportableType)
$query = $query->where('reportable_type' , $reportableType );
return $query;
I had a DB that had a user table and a group table and the group table had a column user_id which made it simply to return a list of users in a group:
$users = User::find()
->where(['{{user}}.group_id' => $group_id])
->all();
Now the user_id column is gone and there is a third table group_user with user_id and group_id columns for the relationship.
I tried this:
$users = User::find()
->innerJoinWith('group_user)
->where(['{{group_user}}.group_id' => $group_id])
but received this error:
User has no relation named "group_user"
But I set the relationship in the User model:
public function getGroupUser() {
return $this->hasOne(GroupUser::className(), ['user_id' => 'id']);
}
What am I missing? This is used in a Humhub API.
I would reprogram your getGroupUser (renaming it to getGroups) relation using viaTable:
public function getGroups() {
return $this->hasMany(Group::className(), ['user_group.id_group' => 'group.id'])
->viaTable('user_group', ['user.id' => 'user_group.id_user']);
}
That would give you the Group(s) a User belongs to. But I think you are aiming to get the Users that belong to a given group, so similarly I would create a getUsers relation in your Group model:
public function getUsers() {
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('group_user', ['group_id' => 'id']);
}
Then:
$group = Group::findOne($id_group);
$users = $group->getUsers()->all();
My tables
Category
id_category
name
Post
id_post
category_id
title
My query:
Post::find()
->select('post.*, c.name AS catname')
->leftJoin('category c', 'c.id_category = category_id')
->all();
The output just shown the table fields Post, is not the field catname.
1) Define a relation in Post model named 'category', so:
public function getCategory() {
return $this->hasOne(Category::className(), ['id_category' => 'category_id']);
}
2) Then when you query the posts, use 'with' if you need to get category name for each post:
$posts = Post::find()
->with('category')
->all();
3) You can access to category name with:
$post->category->name
I created a php function to fetch records from a sql table subscriptions, and I want to add a condition to mysql_query to ignore the records in table subscriptions that exists in table removed_items, here is my code;
function subscriptions_func($user_id, $limit){
$subs = array();
$sub_query = mysql_query("
SELECT `subscriptions`.`fo_id`, `subscriptions`.`for_id`, `picture`.`since`, `picture`.`user_id`, `picture`.`pic_id`
FROM `subscriptions`
LEFT JOIN `picture`
ON `subscriptions`.`fo_id` = `picture`.`user_id`
WHERE `subscriptions`.`for_id` = $user_id
AND `picture`.`since` > `subscriptions`.`timmp`
GROUP BY `subscriptions`.`fo_id`
ORDER BY MAX(`picture`.`since_id`) DESC
$limit
");
while ($sub_row = mysql_fetch_assoc($sub_query)) {
$subs [] = array(
'fo_id' => $sub_row['fo_id'],
'for_id' => $sub_row['for_id'],
'user_id' => $sub_row['user_id'],
'pic_id' => $sub_row['pic_id'],
'since' => $sub_row['since']
);
}
return $subs ;
}
My solution is to create another function to fetch the records from table removed_items and set a php condition where I call subscriptions_func() to skip/unset the records that resemble the records in subscriptions_func(), as the following
$sub = subscriptions_func($user_id);
foreach($sub as $sub){
$rmv_sub = rmv_items_func($sub[‘pic_id’]);
If($rmv_sub[‘pic_id’] != $sub[‘pic_id’]){
echo $sub[‘pic_id’];
}
}
This solution succeeded to skip the items in the table removed_items however this solution makes gaps in the array stored in the variable $sub which makes plank spots in the echoed items.
Is there a condition I can add to the function subscriptions_func() to cut all the additional conditions and checks?
Assuming id is the primary key of subscriptions and subs_id is the foreign key in removed_items, then you just have to add a condition to the WHERE clause. Something like this should work :
...
AND `subscriptions`.id NOT IN (SELECT `removed_items`.subs_id FROM `removed_items`)
...
Not related to your problem :
Your code seems vulnerable to SQL injection : use prepared statement to prevent this.
The original Mysql API is deprecated, it is highly recommended to switch to Mysqli instead.