There is Entities User and Company. Company has user_id.
Now table structure changes and next one user can represent many companies and vice versa (Many to Many eg One to Many - Many to One). This introduces CompanyRepresentative Entity in the middle with fields user_id, company_id and role. Companies user_id will be dropped with that change.
How to make data migration script for that situation? There must be CompanyRepresentative entry for each company present right now that connects same user and company that are connected right now.
Environment is symfony 4 application with Doctrine and Mysql.
Doctrine migrations have functions preUp and postUp. In preUp it is possible to select all needed data and in postUp this data can be inserted to correct places after database structure changes.
For example
public function preUp(Schema $schema)
{
parent::preUp($schema);
$query = "SELECT id, user_id FROM company";
$data = $this->connection->prepare($query);
$data->execute();
foreach ($data as $row) {
$userId = $row['id'];
$companyId = $row['user_id'];
$this->customSQL[] = "($userId, $companyId)";
}
}
public function up(Schema $schema)
{
//Change the schema
}
public function postUp(Schema $schema)
{
parent::postUp($schema);
$SQL = 'INSERT INTO company_rep (user_id, company_id) VALUES ' . implode(', ', $this->customSQL);
$this->connection->executeQuery($SQL);
}
You have to use DoctrineMigrationBundle to do this. look at the documentation here, you should get away with it.
Related
I'm trying to import CSV file in laravel that contains data to be stored in multiple tables in mysql database. Actually I've Contacts with multiple emails, addresses, phones etc so i want them to store in their respective table along with the contactId of the contact newly created from the CSV.
For now insertion in single table is working but when i introduce columns like email, address etc that are to be inserted in other tables, it gives me column not found in Contact table as email address etc column is not there.
Controller Method for Insertion
public function processImport(Request $request){
$data = CsvData::find($request->csv_data_file_id);
$csv_data = json_decode($data->csv_data, true);
foreach ($csv_data as $row) {
$contact = new Contact(); //Insertion in Contact table
foreach (config('app.contact_fields') as $index => $field) {
if ($data->csv_header) {
$contact->$field = $row[$request->fields[$field]];
} else {
$contact->$field = $row[$request->fields[$index]];
}
}
$contact->save(); //Insertion in Contact table
$id = $contact->id;
}
return 'Successfully imported!';
}
Now i want to know is there any way we can separate columns to be inserted into separate tables from the single CSV imported ?
Any help would be highly appreciated.
Thanks
You have to execute multiple queries inside the foreach() loop, because you have multiple tables. Without knowing the both structure of the CSV file and the tables in question it is difficult to specify any further.
i made login_history table with fields user_id foreign for users table , ip_address and created_at i need to very time to login user save it in login_history table now i'm using
Listeners or last_login users using laravel 5.2 with this code
public function handle(Login $event)
{
$user = \Auth::user();
$data = new LoginHistory();
$event->user->$data->user_id = $user->id;
$event->user->$data->created_at = Carbon::now();
$event->user->$data->ip_address = Request::getClientIp();
$event->user->$data->save();
}
**but this not i want
please any one can help for changing this code i have model created
class LoginHistory extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
and i get this error
Cannot use Illuminate\Foundation\Auth\User as User because the name is
already in use
thanks
Considering you have a Model for the LoginHistory pivot table. In any controller method, you can use the following code.
$user = auth()->user();
LoginHistory::create(['user_id'=>$user->id,'ip_address' => Request::getClientIp(), 'created_at'=>Carbon::now()]);
And if you don't have the model, you can use the DB facade to do the same.
You can create a Middleware in laravel in handle method you can insert the data
$event->user->$data->ip_address = \Request::ip(),
I am dealing with the following situation: I have two models, an Employee with id and name fields and a Telephone with id, employee_id and flag fields. There is also an one-to-many relationship between these two models, that is an employee may have many telephones and a telephone may belong to a single employee.
class Employee extends Model
{
public function telephones()
{
return $this->hasMany(Telephone::class);
}
}
class Telephone extends Model
{
public function employee()
{
return $this->belongsTo(Employee::class);
}
}
The Employee model references a table employees that exists in database schema named mydb1, while the Telephone model is related to a telephones table that exists in a different database schema named mydb2.
What I want is to fetch only the employees with at least one telephone of a specific flag eager loaded, using Eloquent and (if possible) not the query builder
What I tried so far without success is:
1) use the whereHas method in the Controller
$employees = Employee::whereHas('telephones', function ($query) {
$query->where('flag', 1); //Fetch only the employees with telephones of flag=1
})->with([
'telephones' => function ($query) { //Eager load only the telephones of flag=1
$query->where('flag', 1);
}
])->get();
What I try to do here is first to retrieve only the employees that have telephones with flag=1 and second to eager load only these telephones, but I get the following query exception because of the different db connections used:
Base table or view not found: Table mydb1.telephones doesn't exist (this is true, telephones exists in mydb2)
2) Eager load with constrains in the Controller
$employees = Employee::with([
'telephones' => function ($query) {
$query->where('flag', 1);
},
])->get();
This method eager loads the telephones with flag=1, but it returns all the employee instances, which is not what I really want. I would like to have a collection of only the employee models that have telephones with flag = 1, excluding the models with telephones = []
Taking into account this post, this post and #Giedrius Kiršys answer below, I finally came up with a solution that fits my needs, using the following steps:
create a method that returns a Relation object in the Model
eager load this new relationship in the Controller
filtered out the telephones of flag != 1 using a query scope in the Model
In Employee model
/**
* This is the new relationship
*
*/
public function flaggedTelephones()
{
return $this->telephones()
->where('flag', 1); //this will return a relation object
}
/**
* This is the query scope that filters the flagged telephones
*
* This is the raw query performed:
* select * from mydb1.employees where exists (
* select * from mydb2.telephones
* where telephones.employee_id = employee.id
* and flag = 1);
*
*/
public function scopeHasFlaggedTelephones($query, $id)
{
return $query->whereExists(function ($query) use ($id) {
$query->select(DB::raw('*'))
->from('mydb2.telephones')
->where('telephones.flag', $flag)
->whereRaw('telephones.employee_id = employees.id');
});
}
In the Controller
Now I may use this elegant syntax a’la Eloquent
$employees = Employee::with('flaggedTelephones')->hasFlaggedTelephones()->get();
which reads like "Fetch all the employees with flagged telephones eager loaded, and then take only the employees that have at least one flagged telephone"
EDIT:
After dealing with the Laravel framework for a while (current version used 5.2.39), I figured, that in fact, whereHas() clauses do work in case of the relationship model exists in a different database using the from() method, as it is depicted below:
$employees = Employee::whereHas('telephones', function($query){
$query->from('mydb2.telephones')->where('flag', 1);
})->get();
#Rob Contreras credits for stating the use of the from() method, however it looks like the method requires to take both the database and the table as an argument.
Not sure if this will work but you can use the from method to specify your database connection within the closure:
$employees = Employee::whereHas('telephones', function($query){
$query->from('mydb2')->where('flag', 1);
})->get();
Hope this helps
Dirty solution:
Use whereExists and scope for better readability.
In Your Employee model put:
public function scopeFlags($query, $flag)
{
$query->whereExists(function ($q) use ($flag) {
$q->select(\DB::raw(1))
->from('mydb2.telephones')
->where('telephones.flag', $flag)
->whereRaw('telephones.employee_id = employees.id');
});
}
Then modify your query like so:
$employees = Employee::flags(1)->get();
I'm new to laravel relationship so many apologizes if it's just dumb question. I'm using a pivot table named users_email on the project to get Emails of users. Pivot table contains the foreign key Uid and Email_id. Uid references users table
primary key and the same as Email_id. I can get the result while joining them using QueryBuilder.
$recent_inbox_email=DB::table('users_email')->
join('email','users_email.email_id','=','email.Id')->
join('users','users_email.Uid','=','users.Id')->
where('users_email.Uid','=',$Uid)->
where('email.draft','<>','true')->
where('email.trash','<>','true')->
where('email.status','=','unread')->count();
here's how I define the relationship in my models
public function getUid()//User Model
{
return $this->hasMany("User_Email",'Uid');
}
public function getEmId()//Email Model
{
return $this->hasMany("User_Email",'email_id');
}
//User_Email Model
public function email()
{
return $this->belongsTo('Email','Id','email_id');
}
public function user()
{
return $this->belongsTo('User','Id','Uid');
}
Now I want to query something like this using Eloquent
$query= select * from users_email inner join
email on users_email.email_id=email.Id
inner join users on users_email.Uid=users.Id
where users.Id=users_email.Uid limit 0,10
foreach($query as $emails)
{
echo $emails->f_name;
echo $emails->Message
}
DB designer Pic
Link to image
Thanks
There are no dumb questions. I'll try to give you an explanation! I'm not a pro, but maybe I can help.
Laravel uses some conventions that are not mandatory, but if you use them, things work like a charm.
For example, as a general recommendation, tables should be named in plural (your table users is ok. Your "email" table should be "emails"). The model, should be named in singular. This is User.php for table users, Email.php for table emails.
"The pivot table is derived from the alphabetical order of the related model names...", in this case "email_user". I repeat, you are not obliged to name them like this, as you can specify the table for the model setting the $table property in the model.
Once you have set up things like this, you only have to add this to your User model:
public function emails()
{
return $this->belongsToMany('Email');
}
And in your Email model:
public function users()
{
return $this->belongsToMany('User');
}
The "User" and "Email" between parentheses is the name of the related model.
And that's it. You can now do this:
$user = User::find(1);
foreach($user->emails as $email) {
echo $email->subject . '<br>';
echo $email->message . '<br>';
}
If you decide not to follow conventions, you can still use Eloquent relationships. You have to set up the relationship like this:
public function nameOfRelation()
{
return $this->belongsToMany('NameOfRelatedModel', 'name_of_table', 'foreign_key', 'other_key');
}
In the case of the User model for example:
public function emails()
{
return $this->belongsToMany('Email', 'users_email', 'Uid', 'email_id');
}
And in the email model, the other way round.
The answer got long! I didn't test the code, but this should give you an idea!
You can always check the official Laravel documentation, it is really helpful!
http://laravel.com/docs/4.2/eloquent
Hope I helped
I have been storing the friend list using the following database structure:
User Id | Friend Id
My problem is that I have an interface that lets them add/delete users from the friend list and the friend list should get saved upon hit.
So would it make sense that I delete all the friends for that user Id and then repopulate the database with the saved friend list ? Sounds a bit counterproductive because if a user adds just one more user, it would be deleting all the friends and re-adding them all.
You can delete all and then repopulate or you can store the initial state of the list of friends, then compare with the final list after user edit.
I recommend you use this function array_diff($array1, $array2), doing something like:
$initial_list = array (1,2,3,4,5);
$list_after_edit = array (1,2,5,6);
$all_new_items = array_diff($list_after_edit,$initial_list);
foreach ($all_new_items as $item) {
// Add to database this item
}
$all_deleted_items = array_diff($initial_list,$list_after_edit);
// Execute this query:
$query = 'DELETE FROM table WHERE `User Id` = <some ID> AND `Friend Id` in (' . implode(',',$all_deleted_items) . ')';