Filter Table, based on field in another table - mysql

I'm stumped with this. I have a table with various fields:
$employees. This, I guess, is what you call a collection, I think, that when I call, returns all employee records in the database (4 records in this example)
Each employee record has the following fields
first_name, last_name, age, other_id
There is another table (or collection), which I'm calling filter table. It is called $other_ids. This has two records, with the following fields - id, id_name.
I want to be able to filter the $employees table so that it only keeps the records, where other_id is equal to one of the two values of id in the filter table- $other_ids
So for example, if the filter table has the following two records:
[{"id":1 "id_name":"one"}, {"id":2, "id_name":"two"}]
And the $employee table contains the records:
[{"first_name":"ted", "surname_name":"stark", "age":35, "other_id":1},
{"first_name":"fred", "surname_name":"strange", "age":30, "other_id":2},
{"first_name":"incredible", "surname_name":"hulk", "age":25, "other_id":3},
{"first_name":"captain", "surname_name":"stone", "age":28, "other_id":2}]
After, the filtering, it should return $employees_filtered should only have records 1, 2, and 4
I've tried doing left-join and using whereHas, and where clauses, but nothing works!

I think you are looking for something like -
$otherId = [1, 2];
$employees_filtered = Employee::with('Others')->whereIn('other_id', $otherId)->get();
Please don't forget to make a relationship with their model.
In Other.php model -
public function Employees()
{
return $this->hasMany('App\Other', 'other_id', 'id');
}
And in Employee.php model -
public function Others()
{
return $this->belongsTo('App\Employee', 'other_id', 'id');
}

Related

fetching data from three tables in laravel

The is the table structure,which basically has three tables,namely expenses,categories and sunbcategories
table expenses
(id,category_id,sub_category_id,date,description,amount)
table categories
(id,category_name)
table subcategories
(id,sub_category_name,category_id)
This is the SQL query that is needed
select expense.date, expense.description, expense.amount,
category.category_name, subcategory.sub_category_name
from expenses as expense,categories as category,subcategories as subcategory
where expense.category_id=category.id and
category.id=subcategory.category_id);
This is the function in Expense model with which I pass the category_id
The same query mentioned above is written in laravel, but I am not able to
fetch the data.
function fetchExpenseData($categoryId)
{
$expense = Expense::select("expenses.*","categories.category_name as
Categoryname","subcategories.Sub_category_name")
->join("categories","categories.id","=","expenses.category_id");
->join("subcategories",function($join)
{
$join>on("subcategories.category_id","=","expenses.category_id")
->on("suncategories.id","=","expenses.sub_category_id")
})->get();
return $expenses;
}
$expenses that are returned will be printed in blade.php.
Can I know what is the mistake
thanks in advance
Hye there ,
You need to add eloquent model for retrieving data fromenter code here three tables
Like
I have School Table , Student Table , Teacher Table
School is relating with both Student and Teacher then we will add relationship
In School Model
`
public function getStudent(){
return $this->hasMany('student_id' , App\Student);
}
public function getTeachers(){
return $this->hasMany('teacher_id' , App\Teacher);
}
In Student table
public function getSchool(){
return $this->hasOne('school_id' , App\School);
}
`
now call data from student
`
$students = Student::with('getSchool.getTeachers')->get()
This Demonstration for what I have get from your Question

When i try to display the count value of one column it counts the no. of arrays stored in a single cell of the same row on the same table

I have written the following function to display a table consisting of
recipe name, description, cusine , ........ ..., ingredients AND LIKES.
Everything works fine but the likes column doesnot show the no. of likes bu instead sows the no. of ingredients of the recipe
public function rec(){
$ing = inglist::all();
$rcusine=recipecusine::all();
$rtype=recipetype::all();
$rec = DB::table('recipe_list')
->select('recipe_list.recipe_id','recipe_list.Recipe_name',
'recipe_list.Recipe_desc','recipe_list.Recipe_duration',
DB::raw('group_concat(ing_list.Ing_name separator ",") as recipe_ingredients'),
'recipe_cusine.Cusine_name', 'recipe_type.Recipe_type_name','recipe_list.image',
DB::raw('count(likerecipes.likecount) as likes'))
->join('recipe_inglist', 'recipe_list.recipe_id','=','recipe_inglist.Recipe_id')
->join('ing_list', 'recipe_inglist.Ing_id','=','ing_list.ing_id')
->join('recipe_cusine', 'recipe_list.Recipe_cusine_id','=','recipe_cusine.cusine_id')
->join('recipe_type', 'recipe_list.Recipe_type_id','=','recipe_type.Recipe_typeID')
->join( 'likerecipes', 'recipe_list.recipe_id', '=', 'likerecipes.recipe_id')
->where('recipe_list.recipe_id','>=','1')
->groupBy('recipe_list.recipe_id', 'recipe_list.recipe_name','recipe_list.recipe_desc','recipe_list.recipe_duration', 'recipe_cusine.Cusine_name','recipe_type.Recipe_type_name','recipe_list.image' )->get() ;
/* var_dump($rec);
die();*/
return view('recipe', ['ingredients'=>$ing, 'cusine'=>$rcusine, 'type'=>$rtype,'recipe'=>$rec]);
}
the output i get is
and this is my likerecipes table
can anyone help me where i am wrong.
Because of the joins, your data is duplicated through the records. Since the likerecipes table seems to store like votes casted one by one identified by an id field uniquely, I would count the distinct likerecipes.id values per group:
'count(distinct likerecipes.id) as likes'
I would also introduce the distinct to the group_concat() to make sure that multiple like votes do not make the same ingridients appear multiple times:
'group_concat(distinct ing_list.Ing_name separator ",") as recipe_ingredients'

How to fetch records from two different tables in laravel5.2

I have two tables 'approval' and 'renewal', both having a common column 'applicant_id'.
When new application comes-in, it stores a data-record in table 'approval' alongwith the 'applicant_id' for whom the record has been added.
Now, when there is a renew applied for that same applicant, the row gets created in the table 'renewal' referencing the 'applicant_id'
Note: There can be a single record in the table 'approval' for a 'applicant_id' but there can be more than one record for the same 'applicant_id' in the table 'renewal'.
Now, my requirement is:
I need to fetch the records from both the table for all the applicants.
Conditions: If there is a data for the 'applicant_id' in both the table and 'renewal' table has multiple row for the same 'applicant_id', then I need to get the records from 'renewal' table only that too the latest one.
If there is no data in 'renewal' table but exists in 'approval' table for the 'applicant_id', then the fetch record should get the data present in 'approval' table.
Basically, if there is record for the applicant in 'renewal' table, get the latest one from there, if there is record present only in 'approval' table, then get that one but the preference should be to get from 'renewal' if exists.
I am trying to do this in laravel 5.2. So, is there anyone who can help me in this?
If you're using Eloquent, you'll have 2 models:
Renewal.php
<?php
namespace App;
use Illuminate\Eloquent\Model;
class Renewal extends Model
{
protected $table = 'renewal';
public static function findMostRecentByApplicantId($applicantId)
{
$applicant = self::where('applicant_id', '=', $applicantId)
->orderBy('date_created', 'desc')
->first();
return $applicant;
}
}
Approval.php
<?php
namespace App;
use Illuminate\Eloquent\Model;
class Approval extends Model
{
protected $table = 'approval';
public static function findByApplicantId($applicantId)
{
$applicant = self::where('applicant_id', '=', $applicantId)
->first();
return $applicant;
}
}
Then, in the code where you want to get the approval/renewal record, use the following code:
if (! $record = Renewal::findMostRecentByApplicantId($applicantId)) {
$record = Approval::findByApplicantId($applicantId);
}
//$record will now either contain a valid record (approval or renewal)
//or will be NULL if no record exists for the specified $applicantId
After few try, I got one way to do it using raw:
SELECT applicant_id, applicant_name, applicant_email, applicant_phone, renewed, updated_at
FROM (
SELECT renewal_informations.applicant_id, renewal_informations.applicant_name, renewal_informations.applicant_email, renewal_informations.applicant_phone, renewal_informations.renewed, renewal_informations.updated_at
FROM renewal_informations
UNION ALL
SELECT approval_informations.applicant_id, approval_informations.applicant_name, approval_informations.applicant_email, approval_informations.applicant_phone, approval_informations.renewed, approval_informations.updated_at
FROM approval_informations
) result
GROUP BY applicant_id
ORDER BY applicant_id ASC, updated_at DESC;
For every single Approval id, there can b multiple records for renewal table suggests you have One to Many relation. which you can define in the your Model like
Approval.php (App\Models\Approval)
public function renewal()
{
return $this->hasMany('App\Models\Renewal', 'applicant_id')
}
Having defined this relation. you can get the records from the table using applicant_id.
$renewal_request_records = Approval::find($applicant_id)->renewal();
This will get all records from renewal table against that applicant_id.
Finding the latest
$latest = Renewal::orderBy('desc', 'renewal_id')->first();
Further Readings Eloquent Relations

Laravel Eloquent ManyToMany getLatest

I built up a pivot table containing ids of tables I want to associate. When I have the id of a specific item, I now want to get the latest entry of this item saved in the pivot table. For example:
Table 1: Tickets
Table 2: Status
Table 3: Ticket_Status (Pivot)
If I add a new entry to the pivot table, I would have something like this:
Pivot
ticketId, statusId
1, 2
1, 3
2, 1
Now I want to receive the latest status in the pivot for Ticket Id 1 for example, so I expect to receive statusId 3 for ticket 1. But how do I do this in Laravel?
Creating the entries for the pivot table works:
public function attachDispatchStatus($id) {
$this->status()->attach($id);
$this->touch();
}
// set fields on the eloquent object and save to database
// raise event that the incident was created.
public function createDispatch($command) {
// Get BodyContent from POST Request
$this->dispatchReference = $command->dispatchReference;
$this->incidentReference = $command->incidentReference;
// Create new Dispatch
$dispatch = Dispatch::create(array(
'dispatch_reference' => $this->dispatchReference,
'incident_reference' => $this->incidentReference
));
$dispatchStatus = DispatchStatus::where('status', '=', 'processing')->first();
$dispatch->attachDispatchStatus($dispatchStatus->id);
return $this;
}
Why don't you use the updateExistingPivot($roleId, $attributes); available in Laravel 5 when editing your tickets ?
This will solve your problem and make your database lighter :)
Check Larvel Doc for some examples on pivot table.
If you don't want to make it like that (because you want to keep an historic of your input), I think you will have to add an dateTime field in your pivot table... Then, just order by date, and you will be fine.

How to get the last updated row using a single query

I searched enough before posting it.
My table structure:
aid | bid | cid | did |
Where aid, bid together are the primary keys.
When I update the value of cid using a where clause for aid, bid I also want to get the did value of the updated row.
Something like this:
$this->db->set('cid', 1, FALSE)
->where(array(
'aid' => $a_id,
'bid' => $b_id
))
->update('my_table')
->select('did');
The above query says:
Fatal error: Call to a member function select() on a non-object in...
I tried this:
How to get ID of the last updated row in MySQL?
Which is like 3 queries.
I'd suggest fetching the values you're about to update, store their IDs in an array, and run an UPDATE with a WHERE id IN (1, 2, ...).
What you're trying to do is not supported by MySQL. You'll need to run at least 2 queries, and since you're fetching the values the first time and already know what values you're updating, then you can also recreate the new row and it's values without using a query after UPDATE.
In your given example:
$this->db->set('cid', 1, FALSE)
->where(array(
'aid' => $a_id,
'bid' => $b_id
))
->update('my_table')
->select('did');
set(), where() and also select() returns an object that builds on the query. However update() return a value which is the results and doesn't have a function called select() and not set() and where() for that matter.