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.
Related
Here, my currently working query is
$results = DB::table('amenities as a')
->leftJoin('amenity_values as av','av.amenity_id','=','a.id')
->leftJoin('units_amenities_values as uav','uav.amenity_value_id','=','av.id')
->leftJoin('units as u','uav.unit_id','=','u.id')
->leftJoin('amenity_pricing_reviews as apr','apr.unit_id','=','u.id')
->select('a.id as amenity_id','a.amenity_name','a.category_id', 'av.amenity_value','u.id as unit_id','u.unit_number','apr.dom','apr.building_id')
->where('a.property_id', $data['property_id'])
->whereIn('apr.building_id', $data['building_ids'])
->whereNull('apr.deleted_at')
->whereNull('u.deleted_at')
->whereNull('av.deleted_at')
->whereNull('a.deleted_at')
->orderBy('a.amenity_name','asc')
->get()
->groupBy(['category_id','unit_id']);
Here, I have joined to a table amenity_pricing_reviews. In this relationship whenever it could not find the related rows in the amenity_pricing_reviews table it is discarding the full rows:
However, I want to get these rows with an empty value for those columns from that table. Something like:
amenity_id => value
amenity_name => value
category_id => value
amenity_value => value
unit_id => value
unit_number => value
dom =>
building_id =>
Also, I have done a lot of other things based on the result of this query so I want to make minimal changes to the structure of the end result.
Your whereIn condition can't succeed if the amenity pricing review doesn't exist, so it effectively changes your left joins into inner joins. Perhaps you want that to be just a condition of the join?
->leftJoin('amenity_pricing_reviews as apr', function($join) { $join->on('apr.unit_id','=','u.id')->whereIn('apr.building_id', $data['building_ids']) })
Try join instead of leftJoin. This should help
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');
}
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.
I'm working on querying my mysql database via doctrine in a symfony2 app. I have a basic table set up that includes an id number ('id'), name ('name'), and a last column for if the person has been contacted ('contacted'), depicted with 0 or 1. I can query and get the number of total inquiries (depicted in the controller with $inquiryCountTotal just fine.
I'm struggling to count the rows that have been contacted. I figure I can either COUNT the rows with a value of 1 in the contacted column or I could just SUM all the rows in the contacted column.
For some reason it seems to be summing the ids, as I have 8 ids and it's spitting a number of 36.
Where am I going wrong? Thanks in advance!
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EABundle:Inquiry')
->findBy(array(), array('id'=>'DESC'));
$inquiryCountTotal = $em->createQuery("
SELECT count(id)
FROM EABundle:Inquiry id
")->getSingleScalarResult();
//This is the part I'm struggling with...
$inquiryCount = $em->createQuery("
SELECT sum(contacted)
FROM EABundle:Inquiry contacted
")->getSingleScalarResult();
return $this->render('EABundle:Inquiry:index.html.twig', array(
'entities' => $entities,
'inquiryCount' => $inquiryCount,
'inquiryCountTotal' => $inquiryCountTotal
));
}
Doctrine is interpreting the alias as the id of the entity.
Try this:
$inquiryCount = $em->createQuery("
SELECT sum(i.contacted)
FROM EABundle:Inquiry i
")->getSingleScalarResult();
i'm new of sqlalchemy,
i'm trying to write this select
select job_id,
machine_id,
state_id,
min(begin_time) as begin_time
from job
where machine_id = 2
and state_id = 2
the first time i've tried to write this..
session.query(Job).filter(and_(Job.begin_time==session.query(func.min(Job.begin_time)),
Job.state_id==2,Job.machine_id == 2)).all()
but return an empty list because it found another min begin_time row .
i've tried another way:
jobRecordSucces = session.query(Job).filter(Job.state_id==2,Job.machine_id == 2)
jobRecordSuccessivo = session.query(jobRecordSucces).filter(jobRecordSucces .begin_time==session.query(func.min(jobRecordSucces.begin_time)))
but the second query return me this error
InvalidRequestError: SQL expression, column, or mapped entity expected -
got '<sqlalchemy.orm.query.Query
object at 0x04491B10>'
thanks in advance :-)