Getting Objects from database in Symfony2 - php

I had read somewhere some day that symfony2/Doctrine2 has a method(i don't remember the method name now) that fetches all "like" objects that we specify..
For example, I have User entity that has userName , password, name, state and city as properties.. For getting all Users who has name = "vinay" and state = "karnataka", the steps goes like this,,
$user = new User();
$user->setName("vinay");
$user->setState("karnataka");
$query = $em->dontKnowTheMethod($user);
$usersList = $query->getResult();
$usersList should contain all the users whose name = "vinay" and state = "karnataka"
I searched for hours but Im not getting that method.. Im sure I had read about that method long back but I cannot recall now..
Thanks in advance..

You should start studying doctrine and symfony.
$user = new User();
$user->setName("vinay");
$user->setState("karnataka");
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$repo = $this->getDoctrine()->getRepository('YourWhateverBundle:User');
$userResult = $repo->findAll(['name' => 'vinay', 'state' => 'karnataka'])
if (!$userResult instanceof User) {
echo 'No result found';
} else {
// Do whatever you want with $userResult
}

Related

Grabbing userID and field upon user creation

I currently have a function that simply creates a user record in the database
$user->name;
$user->address;
$user->save();
Once this is done, I've created an id for them in my users table.
I know I can return $user, but specifically how can I grab the id and name from that to be used in a call like so:
$user->save();
//return $user id and $user name
$update = new UpdateTable($id,$name);
When you call $user->save(), the id (or primary key if it is not id) becomes available via $user->id. So, you'd simply pass the following to your UpdateTable() method:
$user = new User();
$user->name = "Test";
$user->address = "123 Somewhere";
$user->save();
$update = new UpdateTable($user->id, $user->name);
...
Try this code
$user = User::create(['name' => 'name', 'address' => 'Some address']);
$update = new UpdateTable($user->id, $user->name);
or
$update = new UpdateTable($user->getPrimaryKey(), $user->name);

laravel save,update data into two tables

Am having problem updating data into pivot tables.
users[id->autoincrement,username,password,firstname,lastname,lga,email]
class User extends Eloquent
{
public function lga()
{
return $this->HasMany('LGA');
}
}
userslga[id->autoincrement,user_id,lga_id]
public function user()
{
return $this->belongsTo('user');
}
public function lga()
{
return $this->belongsTo('lga');
}
lga[id->autoincrement,lg_name]
class LGA extends Eloquent
{
public function lga()
{
return $this->belongsTo('User');
}
}
When i tried querying relationship,like User::find($id)->lga i could not figure that out.but i eventually made it work using this:
$U_LGA = UserLga::where('user_id',$id)->lists('lga_id');
Now my problem is that i can store data into related tables from my controller like this:
if ($validation->passes())
{
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->type = Input::get('type');
$user->phone = Input::get('phone');
$user->password = Hash::make(Input::get('password'));
$user->save();
//save each users lga
foreach(Input::get('LGA') as $LGS)
{
$userlga = new UserLga;
$userlga->user_id = $user->id;
$userlga->lga_id = $LGS;
$userlga->save();
}
//end
return Redirect::to('/')->with('success','New user profile successfully created');
}
//return json error
return Response::json($validation->messages());
But Updating would be a problem as UserLga::find($id) would not be valid because it the same as select from userlga where id = $id,where as am suppose to be updating all teh row where the user_id is the present user id am editing and add additional lga if more lga was checked.
I need help on how to do this am confused.Or am i getting the concept wrong or is Eloquent relationship query what am suppose to do,
please someone help?
EDIT
I WOULD LIKE TO RUN THE FOLLOWING QUERIES
UserLga::where('user_id',$uid)->lists('lga_id');
I WOULD LIKE TO DO BELOW IN ABETTER WAY TO
$statement2 = "SELECT * FROM facility where LGA_id = '$fulga' ";
//loop through lga id to build query
foreach($LGA_id as $fax)
{
$statement2.= " "."OR"." "."LGA_id=". "'".$fax."'";
}
//FACILITY for User assigned LGA
$facility = DB::Select($statement2);
///////////////////////////////////////////////////////////
//generate all lgaid covered by user
///////////////////////////////////////////////////////////////////////
$ulga = UserLga::where('user_id',$uid)->lists('lga_id');
//remove the first lgaid in array to build query and avoid repetition
$sulga = array_shift($ulga);
// query
$statement = "SELECT * FROM lga where id = '$sulga' ";
//loop through lga id to build query
foreach($ulga as $lga)
{
$statement.= " "."OR"." "."id=". "'".$lga."'";
}
//user assigned lga
$LGA = DB::Select($statement);
AM SORI THIS LOOKS ROUGH A BIT BUT I WANT TO ACHIVE BETTER USING ELOQUENT RELATION QUERY

Insert error on update

I have a good amount of experience with MVC but can't seem to figure what is going wrong here.
I'm trying to update the user's model but for some reason what should be an update is attempting to execute as an insert.
Edit: I'm using this starter site for Laravel which uses Ardent
$user = User::find(Auth::user()->id);
$user->recipient_id = "xxxxxxxxx";
if ($user->save()) {
return true;
} else {
print_r($user->errors()->all()); die();
}
The above outputs
Array (
[0] => The username has already been taken.
[1] => The email has already been taken.
[2] => The password confirmation does not match.
)
Any help would be really appreciated! I have a feeling its something trivial...
Actually while validating it uses rules of the User Model class.
This happens because use of these lines in models.
public $autoHydrateEntityFromInput = true; // hydrates on new entries' validation
public $forceEntityHydrationFromInput = true; // hydrates whenever validation is called
What you have to do is to change the rules dynamically.
$user = User::find(Auth::user()->id);
$user->recipient_id = "xxxxxxxxx";
$user::$rules['username'] = 'required|regex:/^[a-zA-Z\- ]+$/|unique:users,username,'.$user_id;
$user::$rules['email'] = 'required|email|unique:users,email,'.$user_id;
$user::$rules['password'] = 'required';
//this will ignore current username and email
if ($user->save()) {
return true;
} else {
print_r($user->errors()->all()); die();
}

How to get last id for relationships in a transaction between models in Codeigniter?

I have this code inside a function in user-controller. I'm, using Codeigniter.
$name_user = $this->input->post('contact-company');
$company_name = $this->input->post('name-company');
$company_orgnr = $this->input->post('orgnr-company');
$phone_company = $this->input->post('phone-company');
$email_company = $this->input->post('email-company');
//Insert a a new user
$user_info = array(
'username' => $email_company,
'name_user' => $name_user
);
$company_info = array(
'name' => $company_name,
'orgnr' => $company_orgnr,
'phone' => $phone_company,
'email' => $email_company
);
//Insert a new user in db
$query_insertuser = "START TRANSACTION";
//Get sql for inserting a new user
$um = new Usermodel();
$query_insertuser .= $um->getSQLInsert($user_info);
//Get sql for inserting a new company
$cm = new Companymodel();
$query_insertuser .= $cm->getSQLInsert($company_info);
//Get sql for inserting relation between user
//and company (How do I get ID of user and ID of company to use?)
$upm = new Userprofilemodel();
$query_insertuser .= $upm->getSQLInsert();
$query_insertuser .= "COMMIT";
//Do the atual insert
$um->insert($query_insertuser);
It's used for handling a registration through a form. (Validation is done through the form-validation libray)-
Users with username, name_user is stored in a users-table
Companies are stored in a companies-table
Relations between companies and users are stored in a
userprofile-table
I think the code is kind of self-explainatory, but I'm not clear in how to insert the relation in the userprofile-model. I do need the last inserted id for user and the last inserted id for company, but in my code I don't have that because I don't actually insert any users or companies before calling $upm->getSQLInsert();
Or am I doing this incorrectly? Please give me any pointers...
I was obviously not doing this correctly. In case anyone care to bother this is my solution:-)
User-controller (part of it)
//Insert a new user in db
$um = new Usermodel();
$um->startTransaction();
$user_id = $um->insert($user_info);
$cm = new Companymodel();
$company_id = $cm->insert($company_info);
//Insert a new user-profile for newly inserted user
$upm = new Userprofilemodel();
$userprofile_info = array(
'user_id' => $user_id,
'company_id' => $company_id
);
$upm->insert($userprofile_info);
$um->endTransaction();
User-model (part of it)
public function startTransaction() {
$this->db->trans_start();
}
public function endTransaction() {
$this->db->trans_complete();
}
public function insert(array $user_info) {
$this->db->insert('user', $user_info);
return $this->db->insert_id();
}
Company-model (part of it)
public function insert(array $company_info) {
$this->db->insert('company', $company_info);
return $this->db->insert_id();
}
Userprofile-model (part of it)
public function insert(array $userprofile_info) {
$this->db->insert('user_profile', $userprofile_info);
return $this->db->insert_id();
}

Yii Framework $model->save() work for one model only

I try to take the facebook information of a user in my databade. I'm in the UserIdentity to control the athentification of the user and i created this method.
<?php
public function insertFbUser()
{
$user = new User();
$user->fbId = $this->username['id'];
$user->username = $this->username['username'];
$user->email = $this->username['email'];
$user->password = $this->password;
$profile = new Profile();
$profile->first_name = $this->username['first_name'];
$profile->last_name = $this->username['last_name'];
$profile->birthday = strtotime($this->username['birthday']);
$profile->sex = $this->username['gender'];
$profile->fb_updated_time = strtotime($this->username['updated_time']);
$profile->fb_verified = $this->username['verified'];
$profile->fb_educationJson = json_encode($this->username['education']);
$profile->fb_workJson = json_encode($this->username['work']);
var_dump($user->save());
var_dump($profile->save());
}
the var_dump() show me this
boolean true
boolean false
Both models were created with the GII module. I try to only put one prile attribute at a time and it doesn't work too...
There is my DB : http://pastebin.com/u5CNKj9M
Thank you for your help!
print_r($profile->getErrors());
(Update)To get user id after saving:
$user->save();
$user_id = $user->id

Categories