Query builder Call to a member function createQueryBuilder() on a non-object - php

I'm trying to use Query Builder in Symfony2.3 and I keep getting the error:
FatalErrorException: Error: Call to a member function createQueryBuilder()
on a non-object in...line 45
which is the second part of my query,
$query = $tokenobject->createQueryBuilder('t')
->select('t.token','t.user', 't.expirationdate')
->where('t.user = :username','t.token = :token')
->setParameter('username', $Username)
->setParameter('token', $Token)
->orderBy('t.expirationdate', 'ASC')
->setMaxResults(1);
The entire code if it helps:
$confirmationrepository = $this->getDoctrine()
->getRepository('TravelTravelBundle:Confirmation')
->findByuser($Username);
$query = $confirmationrepository ->createQueryBuilder('t')
->select('t.token','t.user', 't.expirationdate')
->where('t.user = :username','t.token = :token')
->setParameter('username', $Username)
->setParameter('token', $Token)
->orderBy('t.expirationdate', 'ASC')
->setMaxResults(1);
$token = $query->getResult();
I know for a fact $confirmationrepository is finding table column'user' properly and that $Username and $Token (being routed into controller) are set and routing properly.
Is there something wrong with my syntax, or is there some other explanation for what is happening?

$confirmationrepository = $this->getDoctrine()
->getRepository('TravelTravelBundle:Confirmation')
->findByuser($Username);
should be
$confirmationrepository = $this->getDoctrine()
->getRepository('TravelTravelBundle:Confirmation');

->findByuser($Username); fetches an array of entries. So $confirmationrepository is an array, and not the repository class you expected. Just omit the findByuser line.

Related

Call to a member function get_courses() on null CI4

Im having an issue using CI4
I kept on getting error "Call to a member function get_courses() on null" even though this function exist on my model. Here's how I code it.
courseModel.php
public function get_courses() //get courses under the teacher
{
$builder = $this->db->table('tbl_course_access');
$builder->select('*');
// $builder->where('user_id', $userid);
// $builder->where('school_id', $schoolid);
//$builder->groupBy('course_id');
$query = $builder->get();
$results = $query->getResult();
return $results;
}
and on my controller I call it like this
Dashboard.php
$temp = $this->courseModel->get_courses();
var_dump($temp);
exit;
note that I called the model properly base on the CI manual
$this->courseModel = model('App\Models\CoursetModel', false);
What did I do wrong or any configuration I need to do on CI4?
My bad, I had typos on my codes that makes the error! Must be a headache doing all the work!

Retrieving data from database and passing it as instance of entity

I'm trying to pass id from query from one database table to another table to which is related.
But, since they are related I have to pass it as instance of the entity(class) to which is related.
This is error I got:
Argument 1 passed to App\Entity\KeywordRating::setKeywordId() must be an instance of App\Entity\Keywords, integer given, called in C:\xampp\htdocs\ratingAPI\src\Service\KeywordRatingService.php on line 26
This is my code:
public function insertRating($params, ObjectManager $manager, KeywordsRepository $keyRep, ProvidersRepository $provRep)
{
$keywordId = $keyRep->checkKeyword(strtolower($params['keyword']))->getId();
$providerId = $provRep->checkProvider($params['provider'])->getId();
$rating = new KeywordRating();
$rating->setKeywordId(<Keywords instance> $keywordId);
$rating->setProviderId(<Providers instance> $providerId);
if($params['attr'] === 'rocks')
{
$rating->setRocksRating($params['rating']);
$rating->setSucksRating(0);
} else
{
$rating->setRocksRating(0);
$rating->setSucksRating($params['rating']);
}
$rating->setRocksVotes(10);
$rating->setSucksVotes(8);
$rating->setSumVotes(18);
$rating->setScore(2.50);
$manager->persist($rating);
$manager->flush();
}
This is sql query:
public function checkKeyword($keyword)
{
return $this->createQueryBuilder('k')
->where('k.keyword_name = :val')
->setParameter('val', $keyword)
->getQuery()
->getOneOrNullResult();
}
checkProvider() is the same, only different parameters.
How do I do that?
Assuming you have a namespace called Entities where you have all your entities classes, you can try something like this:
$entityManager = $this->getDoctrine()->getManager();
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder->select('keyword')
->from('App\Entity\Keywords', 'keyword')
->where($queryBuilder->expr()->eq('keyword.keyword_name', $queryBuilder->expr()->literal($keyword)));
$result = $queryBuilder->getQuery()-> getOneOrNullResult();
return $result;

Laravel ORM select query function load() on null

Here's my function to load submissions created by a user.
public function viewSubs()
{
$user = User::find(Input::get('id'));
$submissions = Submission::find($user)->sortByDesc('created_at');
$submissions->load('user')->load('votes')->load('suggestions.votes');
return view('submissions.index' , compact('submissions'));
}
This returns with an error
Call to a member function load() on null
when there are no records on the submission.
How to handle if there are no submission on the DB?
Just check if its null first using an if statement:
public function viewSubs()
{
$user = User::find(Input::get('id'));
if ($submissions = Submission::find($user)->sortByDesc('created_at')) {
$submissions->load('user')->load('votes')->load('suggestions.votes');
}
return view('submissions.index' , compact('submissions'));
}
Also, depending on your DB structure I'm pretty sure you can cut out a lot of the code by utilising your models' relationships by doing something like this:
$user = User::find(Input::get('id'))
->with(['submissions' => function($query) {
$query->orderBy('created_at', 'asc');
}, 'submissions.votes', 'submissions.suggestions.votes']);
Then pass the $user variable to the view, or:
$submissions = Submission::with('user', 'votes', 'suggestions.votes')
->where('user_id', Input::get('id'))
->sortByDesc('created_at')
->first();
Not entirely sure the code will work perfectly, but I'm sure you can tweak it. The point is your code can be a lot shorter and still/or more readable by using relationships you've already set up.

Doctrine Query Builder Result: not looping correctly

I'm not sure if it's that I'm not doing correctly but this is giving me an error:
I have 2 Entities: Task and TaskUser. They are connected by a onetoMany.
What I want to do is this:
foreach($tasks as $task){
echo $task->getTitle;
echo $task->getTaskUser()->getFirstName();
}
This is my query in the Task Repository:
public function findTasksByUsers($user = false)
{
if($user){
$qb = $this->_em->createQueryBuilder();
$qb
->select('t', 'tu')
->from('\Entities\Task', 't')
->leftJoin('\Entities\TaskUser', 'tu', \Doctrine\ORM\Query\Expr\Join::WITH, 't.id = tu.task')
->where('tu = :user')
->setParameter('user', $user)
->orderBy('t.createDate', 'DESC');
return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT);
}
}
When I do this loop:
$tasks = $this->em->getRepository('\Entities\Task')->findTasksByUsers($user);
foreach($tasks as $task){
echo $task->getTitle();
}
I get the the title of the first task, and then an error like this:
Title of first task
Fatal error: Call to undefined method Entities\TaskUser::getTitle() in D:\sites\db\application\controllers\TasksController.php on line 35
Any idea why this is happening? Thanks!
$qb->select('t', 'tu')
the issue is here as you're selecting both entities.
If you want only Task entity modify your DQL as follows
$qb->select('t')
However, to me, you could only procede that way (in your controller; if you aren't into controller, use DI to access entity manager)
//retrieve all TaskUser object
$em = $this->getDoctrine()->getManager();
$tu_repo = $em->getRepository('YourBundleName:TaskUser');
$tu_array_collection = $tu_repo->findBy(array('user'=>$user));
foreach ($tu_array_collection as $tu) {
$first_name = $tu->getFirstName();
foreach ($tu->getTasks() as $task) {
echo $first_name;
echo $task->getTitle();
}
}
of course you may need to adapt your code with right findBy array, and with correct methods from TaskUser entity

Laravel Eloquent Save Item

When I try to save an item in Laravel it says the following.
Call to undefined method Illuminate\Database\Query\Builder::save()
I have followed the documentation, and i can delete items fine just not update. Is there anything wrong with my code?
public function publishedMain($id, $state){
$userId = Auth::user()->id;
$userAdmin = Auth::user()->admin;
if($userAdmin == "0"){
$clients = Clients::whereRaw('id = ? and parent = ?', array($id, $state));
$clients->active = $state;
$clients->save();
die('not admin');
}else{
$clients = Clients::whereRaw('id = ?', array($id));
$clients->active = $state;
$clients->save();
die('admin');
}
}
Many Thanks
Brent
You call the save() method on the query builder, not on your model.
You're missing the ->first() piece:
$clients = Clients::whereRaw('id = ? and parent = ?', array($id, $state))->first();
Of course, this will get the first client, so naming the variable $clients makes not much sense.
You shall also check if your $clients variable is not null, in which case it didn't find anything.
(btw, your model should be called Client, not Clients)

Categories