I want to make a transaction with 1 transaction many products. but I have a problem only the last index entered on the product. is there a solution?this is my controller
[Model Table][2]
just make sure you are using an array on select query. to fetch all the records.
For eg,
$posts = $this->Employees->find("all")
->contain(["employeePosts" => function($q){
return $q->select(["id", "employee_id", "post_title"]);
}])
->toList();
echo print_r("posts");
here employee_id is a foreign key. and employeePosts is a key I created in EmployeesTable in hasMany()
$this->hasMany("employeeposts")->setClassName("Posts")
Related
I have 2 tables, one with different users, and the second table is an invoice table called "factures" and has a foreign key of userid, I called it client_id, which I am trying to get is the number of clients created_by a certain administrator and who have no invoices yet, here is what I tried:
$clients = User::select('id')
->where([['created_by',$membre_id],['role','Client']])
->orWhere([['updated_by',$membre_id],['role','Client']])
->whereNotExists(function($query)
{
$query->select(DB::raw('client_id'))
->from('factures')
->where('created_by',$member_id);
})->get();
but this query gives me all clients created_by $member_id without exception.
What is wrong with my query?
Did you try the following:
$clients = User::select('id')
->where(function($query) use($member_id){
$query->where([['created_by',$membre_id],['role','Client']])
->orWhere([['updated_by',$membre_id],['role','Client']])
})
->whereNotExists(function($query) use($member_id){
$query->select(DB::raw('client_id'))
->from('factures')
->where('created_by',$member_id);
})
->get();
}
This answer applied the OR condition only between the first two conditions (created_by and updated_by) and its result is AND with the third condition.
I have two tables in laravel. table_2 have a foreign key i-e users_id so I want to fetch data from both tables and remove the duplicate entries. for that purpose I create two queries in my controller
$new=DB::table('tabl-1')
->join('tbl2','tbl1.id','=','tbl2.foreign_key')
->orWhereDate('created_at','<' ,Carbon::today())
->orWhereDate('created_at', Carbon::today())
->orWhereNull('created_at')
->select('tbl_1.created_at as date','tbl1.foreign_key as data_id')
->where('user_id',$users_id)
->get()
->toArray();
$old = DB::table('tbl-2')
->join('tbl1','tbl2.foreign_key','=','tbl1.id')
->where('user_id',$users_id)
->whereRaw('id IN (select MAX(id) FROM tbl2 GROUP BY foreign_key)')
->select('tbl_2.created_at as date','tbl2.foreign_key as data_id')
->get()
->toArray();
$data=array_merge($old,$new);
old array working fine but new array printing duplicate value of data.id , what should I do so I can get all data from old array but when moves in to new array it shows all rows except already show in old array
I'm using Laravel 5 and I need to know the number of books by category, these data I will use on google charts.
I have the code below that I use to find out the number of users by sex. However, the data is in the same table.
$data = DB::table('books')
->select(
DB::raw('category_id as category'),
DB::raw('count(*) as number'))
->groupBy('category')
->get();
$array[] = ['Category', 'Number'];
foreach($data as $key => $value)
{
$array[++$key] = [$value->category->name, $value->number];
}
$test = json_encode($array);
Using the same logic as above, how can I get the number of books by category?
I have the Books table:
ID | Name | ID_CATEGORY
1 Laravel 20
2 Java 20
Category table :
ID | Name
20 Programming
Could you help me in this situation?
You should just group by your ID_CATEGORY column instead of sex.
If you want to construct such array as before, you probably want the name of category. That would be easy if you used Eloquent. You would have $value->category->Name_Category available. If you want those preloaded instead of a query for every value, just add ->with('category') to the query and you'll have it.
If you are not using Eloquent, you should just load the category table separately, key it, and use $categories[$value->ID_CATEGORY]->Name_Category.
Other comments
DB::raw('sex as sex') is equivalent to sex.
++$key seems redundant, you could just push to the end by assigning to $array[].
Array with a header row is not very JSON. Typically you'd have key:value pairs all of the time.
You can construct the array using collection methods.
If you don't have good reasons for the opposite, you should stick to Laravel naming conventions.
I would probably not create an array myself, but do your example as something like this:
$stats = User::select('sex', DB::raw('count(*) as number'))
->groupBy('sex')
->get();
$stats->setVisible(['sex', 'number']);
return $stats;
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
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.