please help me. I want to ask:
Let say I have 2 tables: user_master and people.
Now I am currently build an application in PHP with Laravel 5.1 framework that select the data from user_master table (with some constraint in where clause) and insert into people table.
The code is :
public function handle() {
$results = DB::select(DB::raw("SELECT * FROM user_master WHERE div_id = 1"));
foreach ($results as $res) {
//saving to array
//insert query to table people here.
}
}
My questions are:
How to save the result of select query to array, and
Insert that array into people table using RAW query (INSERT INTO people VALUES (...)).
P.S.: My query is RAW query, not using Eloquent. And please provide answer without Eloquent.
Thank you so much for any answer.
I have done the same scenario like this
$users=DB::table('Users')->where('created_at' ,'>=','2016-09-06')->get();
foreach ($users as $user){
DB::table('users_report')->insert(
array(
'id' => $user->id,
'username' => $user->username,
'lastname' => $user->lastname,
'email' => $user->email,
'created_at' => $user->created_at,
'updated_at' => $user->updated_at,
)
);
}
change your like according to your logic , its works 100% perfectly..
I think that is right
$results = DB::table('user_master')->where('div_id', 1)->get();
if your table and master have the same strucure, you just set the primary key in the below code. If they are not in the same structure, you have to ajust the results to the structure of the people bfore you insert to peopel table.
hope it will helps.
function delete_col(&$array, $offset) {
return array_walk($array, function (&$v) use ($offset) {
unset($v[$offset]);
});
}
public function handle() {
$results = DB::table('user_master')->where('div_id', 1)->get();
delete_col($results, $premiarykeyOfuser_master);
DB::table('people')->insert($results);
}
Related
I am trying to get data in a Yii2 table call Post. This table has an attribute call owner and I want to check whether the value of owner is equal to a particular Value I pass call it userId or the value of owner is equal to the following attribute of the Followship table where the value of the follower attribute of the Followship Table is equal to the the value I pass call it userId.
In implementing the above logically and bit by bit, I have written the following code;
$allpost = Post::find()->all();
$relevantpost = [];
foreach ($allpost as $post) {
if($post->owner == $userId){
$relevantpost[] = $post;
}
else{
$follower = Followship::findOne(['follower'=>$userId, 'following'=>$post->owner]);
if($follower){
$relevantpost[] = $post;
}
}
}
return $relevantpost;
This code works well but I want to write an active query for this such as ;
$allpost = Post::find()
->where(['owner'=>$userId])
->orWhere(['is NOT', $follower = Followship::findOne(['follower'=>$userId]) and 'owner' => $follower->following, NULL])
->all();
or in the worse case,
$allpost = \Yii::$app->db
->createCommand(
"SELECT postId, location, details, created_at FROM Post
WHERE owner = " . $userId. "OR
owner = '0' OR
owner = following IN (
SELECT following FROM Followship WHERE follower = ". $userId . " AND
)
ORDER BY dateCreated DESC"
)
->queryAll();
I keep getting errors with the above queries. I am missing out a fundamental of the Yii2 query builders.
Please any help on this will be greatly appreciated.
First you could make a relation (which connects Post and Followers by post owner) inside your Post class
class Post extends ActiveRecord {
public function getFollowersDataset() {
return $this->hasMany(Followers::className(), ['following' => 'owner']);
}
...
}
And then you can just use it in your queries
Post::find()
->joinWith('followersDataset')
->where(['or',
['owner' => $user_id],
['follower' => $user_id]])
->all()
The condition accept three parameters
[the_condition, the_attribute, the_value]
In case of AND and OR the thing change
[the_condition, first_condition, second_condition]
With the second tried you can make something like that
$allpost = Post::find()
->where(['owner'=>$userId])
->orWhere([
'AND',
['is NOT', $follower, Followship::findOne(['follower'=>$userId]),
['owner', $follower->following, NULL]
])
->all();
You can check in debug bar the querys that you're making, or another way, its to make a mistake in a field, for example if in your where condition you put ->where(['owners'=>$userId]), that trhow an error with the query that you made, so you can see what query you did
I've set up a database and want to update the column status for each row in my UsersController:
I started with this:
User::where('id', '=', 1)->update(['status' => $status]);
This is working, but I need some loop to change all the rows, something like this:
foreach $id from the table
run some code to change individual $status variable
set individual $status value in the 'status' column in each row:
User::where('id', '=', $id)->update(['status' => $status])
end foreach
So for me its unclear how to go through the table via the foreach. Then save the calculated status from my code to each individual id?
#Serge solution is fine for few records but you should be able to use chuck as #ceejayoz suggested
User::chunk(100, function ($users) {
$users->each(function ($user) {
$user->status = getStatus($user);
$user->save();
});
});
Unless the table contains millions of rows... a simple procedural way of doing it is...
$users = Users::get(); // Gets a collection of all users...
foreach ( $users as $user ) {
//compute your status
$user->status = get_your_user_status($user->id);
$user->save();
}
You could also consider using a more functional approach with map for example...
How do i use the following insert into query in laravel 5?
INSERT INTO connection2.table (SELECT * from connection1.table);
I am looking for two different connections, Connection1.table record should goes to Connection2.table.
try
$c1 = DB("Connection1")->select("SELECT * from table")
foreach($c1 as $record){
DB("Connection2")->table("table")->insert(get_object_vars($record))
}
Since laravel 5.7+ insertUsing(array $columns, Closure|Builder|string $query) is available,
DOCS: https://laravel.com/api/5.8/Illuminate/Database/Query/Builder.html#method_insertUsing
therefore you can now make this whole query in Laravel chaining style like
DB::table('newTable')->insertUsing(
['column1', 'column2', 'column3',], // ..., columnN
function ($query) {
$query
->select(['column1', 'column2', 'column3',]) // ..., columnN
->from('oldTable');
// optional: you could even add some conditions:
// ->where('some_column', '=', 'somevalue')
// ->whereNotNull('someColumn')
}
);
DB here is set-up in app.php 'aliases' as
'DB' => Illuminate\Support\Facades\DB::class,
#Wistar, Thanks for reply, with your code $record comes with an object class which is not accepted by insert,
it required the array type.
I have used it as follows:
DB::setFetchMode(PDO::FETCH_ASSOC);
$table_records = DB::connection('Connection1')->select("SELECT * from table");
DB::setFetchMode(PDO::FETCH_CLASS);
DB::connection('Connection2')->table("table")->insert($table_records);
Elaborating on how to chunk results in case of large tables. You can of course chunk as you see fit, 5000 is just an example.
$chunk1 = DB("Connection1")->table("table")->orderBy("id")->chunk(5000, function($c1) {
foreach($c1 as $record) {
DB("Connection2")->table("table")->insert(get_object_vars($record))
}
});
$basket_data = DB::table('baskets')->get();
foreach($basket_data as $records)
{
DB::table('basket_after_payments')->insert(get_object_vars($records));
}
Currently, a criteria BelongsToMany alerts and viceversa. They are related through a pivot table: criteria_id and alert_id.
I am getting all Criteria with the associated Alerts that belongs to the authenticated user, as such:
public function getMatches()
{
$matches = Criteria::whereUserId( Auth::id() )
->has('alerts')
->get();
}
This returns all associated results, whereas now, if a user picks a certain result, I want to be able to show just that. This is what I have so far:
Controller
public function getMatchDetails($alert_id, $criteria_id)
{
$matches = Alert::find($alert_id)
->has('criterias')
->where('criteria_id', $criteria_id)
->get();
}
Which is bringing over the correct variables, however, I am getting a MYSQL error:
Column not found: 1054 Unknown column 'criteria_id' in 'where clause'
select * from `alerts` where `alerts`.`deleted_at` is null and
(select count(*) from `criterias` inner join `alert_criteria` on `criterias`.`id` =
`alert_criteria`.`criteria_id` where `alert_criteria`.`alert_id` = `alerts`.`id`)
>= 1 and `criteria_id` = 7)
Any help would be hugely appreciated.
You could try something like this
public function getMatchDetails($alert_id, $criteria_id)
{
$match = Alert::whereHas('criterias', function ($q) use ($criteria_id) {
$q->where('criteria_id', $criteria_id);
})->find($alert_id);
}
Which will find the alert by id and also check that it has a relationship to criterias meeting those requirements.
I don't know if I understood well the question, but I'm going to try to answer
If you want to pass more than just a variable from the view to the controller, you can do something like this:
View
#foreach($matches as $match)
#foreach($match->alerts as $alert)
<td>{{$alert->pivot->criteria_id}}</td>
<td>{{$alert->id}}</td>
#endforeach
#endforeach
Controller
public function getMatchDetails($id, $var_2 = 0)
{
$myCriteriaIds = Criteria::whereUserId( Auth::id() )
->lists('id');
$match = Alert::find($id)->criterias()
->wherePivot('criteria_id', 'IN', $myCriteriaIds)
->get();
}
Route
Route::post('/users/alert/matches/{id}/{var_2}', array(
'as' => 'users-alert-matches',
'uses' => 'XXXController#getMatchDetails'
));
I'm learning the framework, and now building an application using it.
I need to get all users that have 'user' or 'staff' role, but I couldn't find about it on the documentation.
Help anyone? (I think it's more an ORM problem the the auth module)
I didn't find an easy way to do this using the ORM, but I have a workaround.
This is my code for anyone who might encounter the same problem with me.
// One for each role
$staffs = ORM::factory('role', array('name' => 'staff'))->users->find_all()->as_array();
$managers = ORM::factory('role', array('name' => 'manager'))->users->find_all()->as_array();
// Merge the results
$results = array_merge($staffs, $managers);
May be you should create a separate ORM method for it? Something like this code:
public function get_users(array $roles)
{
$users = DB::select(array($this->_has_many['roles']['foreign_key'], 'id'))
->distinct(TRUE)
->from($this->_has_many['roles']['through'])
->where($this->_has_many['roles']['far_key'], 'IN', DB::expr('('.implode(',', $roles).')'))
->execute($this->_db);
if (count($users) == 0)
{
// return empty list
return array();
}
// now we need only IDs from result
$ids = array();
foreach($users as $columns)
{
$ids[] = $columns['id'];
}
// load users by id
return $this->where($this->_primary_key, 'IN', DB::expr('('.implode(',', $ids).')'))->find_all();
}
$roles is a role_id array (not names!).
PS. I dont remember how to query 'WHERE IN', so I use DB expressions.