I'm new to PHP. I've created classes that represent my database tables (I come from a .Net entity framework background). I would like to run my SELECT statement and pass back a User object. All the examples I've found parse the returned data. Is there a way to just do something like this and have it pass back a User object:
$user = new user();
$user = $mysqli->query($query, MYSQLI_STORE_RESULT);
return $user;
or do I have to parse the result first?
Note: all the fields in the user class match the fields in the database
I.E. $user->UserName = [user].[UserName]
Try use PDO with "fetchobject":
$statement = $db->query($query);
$user = $statement->fetchObject('User');
http://www.php.net/manual/en/pdostatement.fetchobject.php
or convert (cast) each "row" of data to User Object (example function)
or try a ORM PHP solution
Related
I would like to know if it's possible to return a MySQL stored procedure call as an eloquent object.
The below call works fine for me, but $result always returns an array instead of the usual Eloquent object.
$result = DB::select('call bookings_by_voucher()');
Does anyone know how to return this as an object, so that I can use ->count(), ->get() etc.
You must pass the array into a new instance of your eloquent object.
$booking = new Booking($result);
A late question, but if anyone else needs this:
Booking::fromQuery('call bookings_by_voucher()');
The only problem is you can't do further sql operations like where, limit, etc, since you can't manipulate a stored procedure directly, eg: you can't do "call bookings_by_voucher() where active = 1 limit 200". You can use laravel collection operations though.
https://laravel.com/docs/5.4/eloquent-collections
you can use eloquent MODEL. It return an object .
ex.
$user = app\ModelName::all()->count();
get(),count() and other aggregate function works with Models
I am familiar with using Yii to call records, but how would I go about taking an existing active record model and appending more information to it using a different query?
For example:
$user = User::model()->findByPk(1);
$user[] = User::model()->findByPk(2);
Basically, I am trying to add model $user1 + $user2. In this type of example, I want to have both users 1 and 2 in the same $user model. (I have not actually tried the code above, but I do not think it would work like that.) The information obtain from both requests would be exactly the same format.
Be aware that that I am not trying to get both users. I know how to do that. In this question, I am attempting to take an existing model and add more data to it to form one model by merging the two models together.
There is no built in Yii way to do what you are trying to accomplish. Instead, you can your model with some custom enhancements.
private $additionalUsers = array();
public function addAdditionalUser($user)
{
$this->additionalUsers[] = $user;
}
public function getAdditionalUsers()
{
return $this->additionalUsers;
}
Then you use this as follows:
$user = User::model()->findByPk(1);
$user->addAdditionalUser(User::model()->findByPk(2));
However, without knowing more of what you mean by "merge" the models, this may or may not be what you are looking for. An example of how you expect to use the merged model would be useful if this answer doesn't suit your needs.
You can do this:
$users = array();
$user1 = User::model()->findByPk(1);
$user2 = User::model()->findByPk(2);
array_push($users, $user1);
array_push($users, $user2);
Now $users is an array that contains two objects.
You can use
$users = User::model()->findAllByPk(array(1,2));
which will return and array of usermodels
I am creating articles in Joomla! programmatically using JTable.
Since I have a lot of articles that need to get synchronized periodically, I need to check each article if it already exists before inserting it (otherwise it produces errors).
What is the best way to do so?
My idea was to retrieve all articles from database and compare unique fields. But problems (blank page) occured while retreiving the articles. Here is the code:
function getExistingArticles(){
// Create a new query object.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*')->where('`a.created_by_alias`= `article_synchronizer`'); // Prepare query.
$query->from('`#___categories` AS a');
// Reset the query using newly populated query object.
$db->setQuery($query);
$articles = $db->loadObjectList(); // Execute query, return result list.
return $articles;
}
If this is the "best" way in Joomla! to check if a certain article already exists, where is the problem in this code, that results in a blank page?
Otherwise which is the best way to check if a Joomla! article with a certain content already exists?
I haven't tested your query, but I would suggest quoting column names and values using Joomla's API like so:
function getExistingArticles()
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('a.*')))
->from($db->quoteName('#__categories', 'a'))
->where($db->quoteName('a.created_by_alias') . ' = ' . $db->quote('article_synchronizer')); // Quoted query.
$db->setQuery($query);
$articles = $db->loadObjectList();
return $articles;
}
I've fixed your query a little. You were using 3 underscores when defining the table prefix (only 2 should be used). The where and from clauses were also the wrong way round.
I find very annoying to have to fetch an object by id from database every time I want to add it to a relationship. Is there a way to add an object to a a relationship by id instead of adding the whole object?
This is my actual code:
...
$person = $em->getRepository("Person")->findOneById($id);
$me->getPersons()->add($person);
...
I would like to have something like this:
...
$me->getPersons()->add($id);
...
Then I would be saving one trip to the database! Which I like better! Is it possible?
You don't have to do that actually. You can get reference object like so:
$person = $em->getReference("Person", $id);
$me->getPersons()->add($person);
Doctrine will not make a query for Person but will instead return an reference proxy object for person with that id. If you, however do:
$person = $em->getReference("Person", $id); // 0 queries
$person->getId(); // Still 0 queries
$person->getSomeField(); // query fired
Doctrine will trigger lazy load if you try to get some field that has to be fetched from database.
See docsEntityManager::getReference method
I am having an issue that I haven't seen before with a new Symfony2 project. I have setup the authentication for the new application using a normal form login, and that works fine.
The problem is when I try to query the database using either doctrine DQL or raw SQL in the action of a controller. Just for testing, I am trying to query the same user table that the authentication uses. I made it a very simple query that SHOULD have results, but when the query is executed, no results are returned.
This is how I am doing the query:
$sql = "SELECT * FROM sys_user";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$user = $stmt->fetchAll();
$return = array("success"=>true,"data"=>$user);
$response = new JsonResponse($return );
return $response;
I have performed this query directly on my database, and it definitely does have data, so I am lost to why this won't work. In my mind, if the authentication mechanism can pull data from the database, it doesn't make sense that I am unable to fetch data from the same table.
There is no error, just an empty result.
I don't know if posting from my config files will help, because it seems to me like everything is setup correctly, just the query isn't returning data.
Has anyone experienced this? Any ideas what I can do?
I am using:
Symfony 2.3.6,
PHP 5.3.27,
Postgres 9.2,
IIS 7.5
EDIT:
Here is my query using DQL. I would prefer to use DQL for maintainability.
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT u
FROM MyCoreBundle:SysUser u'
);
$user = $query->getResult();
This returns an empty result for each row in the table. So doctrine knows how many rows there are, but won't return the objects. Is there something I am missing here? This is a modified snippet straight from the symfony docs Here so I don't know what could be wrong.
This does the same thing as well:
$user = $this->getDoctrine()
->getRepository('MyCoreBundle:SysUser')
->findAll();
The problem is with the response. This was how the response was returned:
$response = new JsonResponse($user);
This uses json_encode which expects and assosiative array as the parameter. What needed to be done is this:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT u
FROM MyCoreBundle:SysUser u'
);
$user = $query->getArrayResult();
This solves the problem.
Add the following code after $stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
I think this might be the problem.