Bulk Insert in Laravel 5.3 - laravel

$list = [];
foreach($RoleDetails["Data"]["Permissions"] as $Permission) {
$MyModel = new UserRolePermissionModel();
$MyModel->UserID = $User->UserID;
$MyModel->RolePermissionID = $Permission->RolePermissionID;
$MyModel->IsActive = $Permission->IsActive;
array_push($list, $MyModel);
}
\DB::table('tbluserrolepermission')->insert($list);
Below are the error details
QueryException {#293 ▼
#sql: "insert into `tbluserrolepermission` (`0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
#bindings: array:18 [▶]
#message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `tbluserrolepermission` (`0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`) values ({"UserID":21,"RolePermissionID":19,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":20,"IsActive":0,"IsProtectionAvailable":0,"IsProtectionReadOnly":1}, {"UserID":21,"RolePermissionID":21,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":22,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":23,"IsActive":0,"IsProtectionAvailable":0,"IsProtectionReadOnly":1}, {"UserID":21,"RolePermissionID":24,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":25,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":26,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":27,"IsActive":0,"IsProtectionAvailable":0,"IsProtectionReadOnly":1}, {"UserID":21,"RolePermissionID":28,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":29,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":30,"IsActive":0,"IsProtectionAvailable":0,"IsProtectionReadOnly":1}, {"UserID":21,"RolePermissionID":31,"IsActive":0,"IsProtectionAvailable":0,"IsProtectionReadOnly":1}, {"UserID":21,"RolePermissionID":32,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":33,"IsActive":0,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":34,"IsActive":1,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}, {"UserID":21,"RolePermissionID":35,"IsActive":1,"IsProtectionAvailable":0,"IsProtectionReadOnly":1}, {"UserID":21,"RolePermissionID":36,"IsActive":1,"IsProtectionAvailable":1,"IsProtectionReadOnly":0}))"
#code: "42S22"
#file: "C:\xampp\htdocs\AS4\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
#line: 761
-previous: PDOException {#356 ▶}
+errorInfo: array:3 [▶]
+"previous": PDOException {#356 ▶}
-trace: {▶}
}

It is not working, because you are not providing an array of arrays with only the values matching the column names to populate the database with.
Example
Lets say you want to populate an array of users and save them to the database. The following example would do that.
DB::table('users')->insert([
['email' => 'taylor#example.com', 'votes' => 0],
['email' => 'dayle#example.com', 'votes' => 0]
]);
Note that email and votes in the above example are 2 columns in the users table. Note also that only an array of other arrays are passed to the insert method. What you are trying to insert is actually an array of eloquent model objects.
Source: https://laravel.com/docs/5.3/queries#inserts

I fixed it like below.
foreach($RoleDetails["Data"]["RolePermissions"] as $RolePermission) {
$data = [
'UserID' => $User->UserID,
'RolePermissionID' => $RolePermission->RolePermissionID,
'IsActive' => $RolePermission->IsActive,
'IsProtectionAvailable' => $RolePermission->IsProtectionAvailable,
'IsProtectionReadOnly' => $RolePermission->IsProtectionReadOnly
];
array_push($list,$data);
}
\DB::table('tbluserrolepermission')->insert($list);
or it could be like this.
UserRolePermissionModel::insert($list);

Can you try this?
UserRolePermissionModel::insert($list->toArray());
OR
DB::table('table')->insert($list->toArray());

Related

JDBC connection for HANA with input parameters

I am trying to extract some tables with using RJDBC connection. However, in the tables, there are some must input variables that I need to give. I need to find a way that extract these input parameters. As I understand, then I can extract the tables I want. However, I don't know how to find and extract them.
qry <- 'select * from "__tablename__"(
PLACEHOLDER."$$variable1$$" => ?,
PLACEHOLDER."$$variable2$$" => ?,
PLACEHOLDER."$$variable3$$" => ?,
PLACEHOLDER."$$variable4$$" => ?,
PLACEHOLDER."$$variable5$$" => ?)'
data <- dbGetQuery(conn, qry, variable1, variable2, variable3, variable4, variable5)

Laravel save() is not update record

I am trying to update records in the database table if record already exists. Insert new record if record is not to the database table.
I have written below code for that
DB::enableQueryLog();
$user->userCommission()->save(new UserCommission($input['commission']));
dd(DB::getQueryLog());
when EnableQueryLog it's always show insert query, If record is already in the table.
Here is my query..
array:1 [▼
0 => array:3 [▼
"query" => "insert into `user_commissions` (`created_by`, `status_id`, `percent`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?)"
"bindings" => array:6 [▼
0 => "1"
1 => "1"
2 => "0.10"
3 => 21
4 => "2016-08-13 08:07:45"
5 => "2016-08-13 08:07:45"
]
"time" => 2.57
]
]
In above query user_id 21 record already in the table although Save() insert record to the database.
where am i wrong with this code?
May I have to apply unique key to the table?
Require at least one unique column to find or update table record
$userCommission = UserCommission::firstOrNew(array('created_by' => 1));
$userCommission->status_id = 1;
$user()->userCommission()->save($userCommission);
There is a alternative one way step to check this.update_at & created_at will be inserted by laravel default
userCommission::updateOrCreate([
'user_id' => 21
],[
'created_by' => 1,
'status_id' => 1,
'percent' => "0.10",
'user_id' => 21,
]);

Two wherehas in a Laravel Eloquent query

I have the following query, simplified below.
$property = Property::whereHas('features', function ($q1) use ($features) {
$q1->where(function ($sub) use ($features) {
$sub->whereIn('features.FeatureID', $features);
});
$q1->groupBy('PropertyID');
$q1->having('count(*)', '=', count($features));
})
->whereHas('Week', function ($q) use ($nights) {
$q->where(function ($sub) use ($nights) {
$sub->whereIn('priceAvailDate', $nights);
});
$q->groupBy('PropertyID');
$q->having('count(*)', '=', count($nights));
})
->get();
If I take one whereHas out, I get the expected collection returned. If I take the other out I get the expected result.It is when they are together I have nothing returned. I assume it is down to having two count(*). I know I have data where both whereHas is true.
SQL output is
select * from `tblproperties` where (select count(*) from `features` inner
join `propertyfeatures` on `features`.`featureid` =
`propertyfeatures`.`FeatureID` where `propertyfeatures`.`PropertyID` =
`tblproperties`.`PropertyID` and (`features`.`FeatureID` in (?)) group by
`PropertyID` having `count(*)` = ?) >= 1 and (select count(*) from
`tblpriceavail` where `tblpriceavail`.`propertyID` = `tblproperties`.`PropertyID`
and (`priceAvailDate` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)) group by
`PropertyID` having `count(*)` = ?) >= 1
Fixed, although not 100% sure why. Using havingRaw instead of having worked.
i.e. changing the $q->having('count(*)', '=', count($nights));
to $q->havingRaw('count(*) = ' . count($nights));

Laravel Eager Loading, filtering and limit column fields does not work

I want to filter my selection of columns in my channels hasmany relation as well filtering it using where method but to no avail. Any idea?
$data['users'] = Users::with(array('Channels' => function($q){
$q->where('is_default','=', 1)->select(array('channel_name', 'channel_id'));
}))->get(array('id'));
But this works perfectly fine.
$data['users'] = Users::with(array('Channels' => function($q){
$q->where('is_default','=', 1)
}))->get(array('id'));
I tried putting the select method first before the where method still does not work
EDIT:
These are SQL queries executed which is really what I wanted however it does not fill up the relations property.
select created_at, id, name, referrer from users where status = ? limit 10 offset 0
select channel_name, channel_id from channels where channels.user_id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) and is_default = ?
You may try this
$data['users'] = Users::with(array('Channels' => function($q){
$q->select('id, channel_name', 'user_id')->where('is_default','=', 1);
}))->get();
If you want to select columns in get() then make sure you select the associated key for channels table, for example, assuming that user_id is the foreign key in chennels table so you can do it using this:
$data['users'] = Users::with(array('Channels' => function($q){
$q->select('id, channel_name', 'user_id')->where('is_default','=', 1);
}))->get(array('id'));
If you don't select the primary key in the main query and foreign key in the sub query then with will not work. In both querys/select the related keys should be available.

How do I create a prepared insert statement in Sequel?

I am attempting to create a prepared insert statement in Sequel and I am as far as
db[:registration].prepare(:insert)
=> <Sequel::Mysql2::Dataset/PreparedStatement "INSERT INTO `registration` () VALUES ()">
How do I create a statement that is something like the following:
INSERT INTO `registration` (`name`, `email`) VALUES (?, ?)
The documentation is a little bit obtuse and I can't find any examples online.
Figured this out looking at their rspecs:
statement = db[:registration].prepare(:insert, :prepared_statement_name, :email => :$email, :name => :$name)
statement.call(:name => "foo", :email => "foo#bar.com")
NOTE
The keys that are passed to .call correspond to the values passed in the hash in prepare. So this would work too:
statement = db[:registration].prepare(:insert, :prepared_statement_name, :email => :$e, :name => :$n)
statement.call(:n => "foo", :e => "foo#bar.com")
ds = db[
"INSERT INTO `registration` (`name`, `email`) VALUES (?, ?)",
name, email
]
ds.call(:insert)

Resources