I am trying to use the count_all() method in kohana 3.3 to count all the rows of a table where the id equals a user_id. Here is my controller
public function action_get_messages()
{
$user_id = $this->request->param('id');
$messages = new Model_Message;
if ($user_id)
{
$messages = $messages->where('user_id', '=', $user_id);
$messages->reset(FALSE);
$message_count = $messages->count_all();
}
else
{
$message_count = $messages->count_all();
}
$pagination = Pagination::factory(array(
'total_items' => $message_count,
'items_per_page' => 3,
));
$pager_links = $pagination->render();
$messages = $messages->get_all($pagination->items_per_page, $pagination->offset, $user_id);
$this->template->content = View::factory('profile/messages')
->set('messages', $messages)
->set('pager_links', $pager_links);
}
But when i run the code i get these error message:
"Database_Exception [ 1054 ]: Unknown column 'COUNT("*")' in 'field list' [ SELECT COUNT("*") AS records_found FROM messages
AS message WHERE user_id = '2' ]"
What does this error mean and where is the error in my code?
Thanks in advance!
The error is on line 1054, which I would guess is the count_all() call.
I'm confused as to why you are calling a reset() on your object. This may be causing issues. You are also casting the object to itself, which is unnecessary. That section of code could look like this:
if ($user_id)
{
$messages->where('user_id', '=', $user_id);
$message_count = $messages->count_all();
}
I would advise using the ORM::factory to build your new models in the first place.
The Kohana documentation isn't great, but I would advise reading and looking through the ORM User Guide as ORM will save you a hell of a lot of time in the long run, especially if it's a large project.
Related
I'm trying to do this SQL query with Doctrine QueryBuilder:
SELECT * FROM events WHERE NOT id in (SELECT event_id FROM ues WHERE user_id = $userID)
The UserEventStatus has foreign keys from User and event, as well as an integer for status.
I now want to query all events that dont have an entry in UserEventStatus from an particular User.
My function for this in the EventRepository looks like this:
public function getUnReactedEvents(int $userID){
$expr = $this->getEntityManager()->getExpressionBuilder();
$originalQuery = $this->createQueryBuilder('e');
$subquery= $this->createQueryBuilder('b');
$originalQuery->where(
$expr->not(
$expr->in(
'e.id',
$subquery
->select('ues.user')
->from('App/Entity/UserEventStatus', "ues")
->where(
$expr->eq('ues.user', $userID)
)
)
)
);
return $originalQuery->getQuery()->getResult();
}
But i get an error that says:
Error: Method Doctrine\Common\Collections\ArrayCollection::__toString() must not throw an exception, caught ErrorException: Catchable Fatal Error: Object of class Doctrine\ORM\EntityManager could not be converted to string (500 Internal Server Error)
Can anyone help me or point me to right point in the docs? Cause i failed to find something that describes my problem.
And another thing is, that I don't know if its possible, but it would be nice. Can I somehow make direct Object requests? I mean not with the string App/Entity/UserEventStatus but with something like UserEventStatus::class or something.
Thanks for your help in advance. :)
EDIT: It has to be $originalQuery->getQuery()->getResult() of course.
If its like it was with $subquery instead i recive [Semantical Error] line I0, col 41 near 'App/Entity/UserEventStatus': Error: Class 'App' is not defined. (500 Internal Server Error)
Second EDIT:
$expr = $this->getEntityManager()->getExpressionBuilder();
$queryBuilder = $this->createQueryBuilder('e');
$subquery= $this->createQueryBuilder('b')
->select('ues.user')
->from('UserEventStatus', "ues")
->add('where', $expr->eq('ues.user', $userID));
$originalQueryExpression = $expr->not($expr->in('e.id', $subquery));
$queryBuilder->add('where', $originalQueryExpression);
return $queryBuilder->getQuery()->getResult();
Third EDIT: Thanks to #Dilek I made it work with a JOIN. This is the final Query:
$queryBuilder = $this->createQueryBuilder('e')
->leftJoin('App\Entity\UserEventStatus', 'ues', 'WITH', 'ues.user=:userID')
->setParameter('userID', $userID)
->where($expr->orX($expr->not(
$expr->eq('e.id','ues.event')
),
$expr->not($expr->eq('ues.user', $userID)))
);
return $queryBuilder->getQuery()->getResult();
Building AND WHERE into a Query
public function search($term)
{
return $this->createQueryBuilder('cat')
->andWhere('cat.name = :searchTerm')
->setParameter('searchTerm', $term)
->getQuery()
->execute();
}
simple is: ->where('cat.name = :searchTerm')
UPDATE :
I think you need to use where in
$qb->add('where', $qb->expr()->in('ues.user', $userID));
And WHERE Or WHERE
I made a search page with filters. In Laravel the code is:
$select = [
'car.id as id',
'car.car_name as name'
];
$q = Car::where('car.active',1);
if ($price) {
$select = array_merge([
DB::raw("(select p.car_price * $variable from prices p where p.car_id = car.id) as unique_price"
)],$select);
}
$q->select($select);
$q->having('unique_price', '>=', 2000);
I am using postgresql as laravel database and i get the error unique_price does not exist.
then i write:
dd($q->get());
and the "unique_price" column exists.
What is the problem? how can i fix it? in mysql works.
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 have an application with a basic forum system where users can "like" a topic multiple times. My models extend Eloquent and I'm trying to get the sum of votes a user has for a specific topic... Basically, I'm trying to accomplish something like:
$votes = Auth::user()
->votes->has('topic_id', '=', $topic->id)
->sum('votes');
However, when executing this, I get the following error...
Call to a member function sum() on a non-object
I've also tried
public function show($forumSlug, $topicSlug)
{
$topic = Topic::whereSlug($topicSlug)->first();
$votes = Topic::whereHas('votes', function ($q) use ($topic)
{
$q->where('topic_id', '=', $topic->id)->sum('votes');
});
dd($votes);
}
However, with that I receive an error stating:
Unknown column 'ideas.id' in 'where clause' (SQL: select sum(votes)
as aggregate from votes where votes.idea_id = ideas.id and
idea_id = 1)`
You may try something like this (Not sure about your relationship but give it a try):
$topic = User::with(array('topics' => function ($query) use ($topic_id) {
// $query = Topic, so it's: Topic::with('votes')
$query->with('votes')->where('topics.id', $topic_id);
}))->find(Auth::user()->id)->topics->first();
// Count of total votes
dd($topic->votes->count());
P/S: If it doesn't work then please post your model's relationship methods.
I managed to get it working, though I'm not sure I like this approach. I'd love to hear if anyone knows of a better way of doing this...
Basically, I used my relationships to filter() the votes and then used sum() on the filtered collection.
public function show($forumSlug, $topicSlug)
{
$userId = is_null(Auth::user()) ? false : Auth::user()->id;
$topic = Topic::whereSlug($topicSlug)->first();
$votes = $topic->votes->filter(function ($votes) use ($userId)
{
return $votes->user_id == $userId;
})->sum('votes');
return View::make('forums.topics.show', compact('topic', 'votes'));
}
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.