I have this Laravel 4.2 Eloquent Query
$m[] = Auth::user()->id;
foreach ($friends as $friend) {
$m[] = $friend->added_user;
}
$news = NewsFeed::whereIN('user_id', $m )->take($limit)->skip($offset)->get();
Actual query:
$news = NewsFeed::whereIN('user_id', array( 'CUS_6367VkCX5i243656TwM3', 'CUS_G530t786S1GVwlcJ3Nw1', 'CUS_xks5oi3dy2C0sa02usD2' ) )->take(10)->skip(5)->get();
Database:
It should return something, Newsfeed Table has datas in it but
result is none, its empty.
What is wrong with my Laravel 4.2 Eloquent Query?
BUT WHEN I DO THIS:
$news = NewsFeed::whereIN('user_id', $m )->get();
it returns a result, without limit and skip.
It seems that $m[] = $friend->added_user; is where you go wrong
dd($friend->added_user)
You will see in your array $m objects of users. However, in your query what's needed is the user_id of added_user.
In this case, you should modify as follows:
$m[] = $friend->added_user()->first()->user_id; //it depends on what your added_user returns, if it returns an array, you should loop over it to get all ids or use ->lists('user_id') to get an array of user_id
Hope it helps
This will do the trick:
$news = DB::select( DB::raw(" SELECT * FROM `news_feed` WHERE `user_id` IN ('CUS_6367VkCX5i243656TwM3', 'CUS_G530t786S1GVwlcJ3Nw1', 'CUS_xks5oi3dy2C0sa02usD2') LIMIT 5, 5 ") );
Related
In my Laravel code I use DB to access to database. In controller function named showTeacherList I am trying to get all works of every teacher. But Laravel returns this error. When I dump query, copy past it to phpmyadmin and run, it works. My code:
function showTeacherList($login){
$select_result = DB::select('select id, name from kafedra where login = ?', [$login]);
$kafedra_id = $select_result[0]->id;
$teachers = DB::select('select id, name from teacher where kafedra_id = ?', [$kafedra_id]);
$teacher_works = [];
$i = 0;
foreach ($teachers as $teacher) {
$teacher_works[$i] = DB::select('select * from work where teacher_id = ?' [$teacher->id]);
$i++;
}
return view('kafedra/teacher_list', ['login' => $login, 'name' => $select_result[0]->name, 'teachers' => $teachers, 'teacher_works' => $teacher_works]);
}
Please help, thanks
You have a syntax error in your DB::select statement, specifically within your foreach loop. You've missed a comma separating your query and bindings.
Replace:
$teacher_works[$i] = DB::select('select * from work where teacher_id = ?' [$teacher->id]);
With:
$teacher_works[$i] = DB::select('select * from work where teacher_id = ?', [$teacher->id]);
I'm using Symfony 4 with EasyAdmin and I need to make a select query that retrieve all the users, but I want the connected user to be selected as the first result.
I don't know how to proceed at all. I was thinking maybe do multiple select in the same query ? but I don't even know how to do this.
So far I have this :
$repo = $this->getDoctrine()->getRepository(User::class);
$authUser = $this->getUser();
$queryBuilder = $repo->createQueryBuilder('u');
return $queryBuilder;
// Doctrine createQueryBuilder looks like this
public function createQueryBuilder($alias, $indexBy = null)
{
return $this->_em->createQueryBuilder()->select($alias)->from($this->_entityName, $alias, $indexBy);
}
EDIT : I imperatively need to return the queryBuilder object, not the result set, that's why it's tricky.
An approach that will query all users, but gives you an array in the order you describe:
$users = $userRepository->findall();
foreach ($users as $user) {
$this->getUser() == $user ? $currentUser[] = $user : $otherUsers[] = $user;
}
$myUserList = array_merge($currentUser, $otherUsers);
Two sidenotes: 1: This queries all users and then splits them. I'm not sure if this could be what you want. 2: if no user is currently logged in this code will not work because $currentUser won't be defined. Of course, you can change it so it will also work when no user is logged in.
Edit based on the fact that returning the querybuilder is imperative:
You can use CASE to test and create a property, which you can hide with AS HIDDEN in your query and then order by this hidden property like so:
public function currentUserFirst($userId){
$qb = $this->createQueryBuilder('u')
->select('u, CASE WHEN u.id = :userId THEN 0 ELSE 1 END AS HIDDEN order')
->setParameter('userId', $userId)
->orderBy('order', 'ASC');
return $qb;
}
As the first comment pointed out, you will need to use a UNION, which is not supported in DQL.
Therefore your only option is to use a native query using the Connection which you need to get from the EntityManager.
It would look something like this:
$id = $this->getUser()->getId();
$sql = 'SELECT * FROM `users` WHERE `id` = :id UNION SELECT * FROM `users` WHERE`id` != :id'
$users = $this->getDoctrine()->getConnection()->fetchAll($sql, compact('id'));
You can use setMaxResults:
$qb->andWhere('q.start <= :start')
->setParameter(':start', $value)
->setMaxResults(1)
;
I created 2 textension in magento along with 2 different tables. First extension store data in table-1 while second second extension store data in table-2. Now i want to display data in first extension by LeftJoin. It show data without leftjoin from first table but not showing data with leftjoin from both the tables.
This code in block.php
public function methodblock()
{
$collection = Mage::getModel('test/test')->getCollection();
$returnCollection = $collection->getSelect()
->joinLeft('magento_answer', 'id_pfay_test=question_id',
array('*'), null , 'left');
return $returnCollection;
}
On Layout side. dislplaydata.phtml
<?php
$collection = $this->testmethodblock();
foreach($collection as $rows {
echo $rows ->getData('name');
}
I Got the answer. I use the custom query which works for me.
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$qTable = $resource->getTableName('pfay_test');
$aTable = $resource->getTableName('answer/answer');
$query = 'SELECT * FROM '.$qTable.' q left join '.$aTable.' a ON a.question_id=q.id_pfay_test';
$results = $readConnection->fetchAll($query);
return $results;
Sorry for modifying this question (to all those who have answered here). The question was in fact wrong.
$query = User::find(1)->books(); //books() is "return $this->hasMany('Book');"
$query_for_counting_history_books = clone $query;
$query_for_counting_geography_books = clone $query;
$number_of_history_books = $query_for_counting_history_books->where('type', '=', 'history')->count();
$number_of_geography_books = $query_for_counting_geography_books->where('type', '=', 'geography')->count();
$books = $query->paginate(10);
I want $books to be queried as:
SELECT * FROM books WHERE user_id=1 limit 10;
But its output is:
SELECT * FROM books WHERE user_id=1 and type="history" and type="geography"
limit 10;
Am I missing something about Clone here?
What should be done for this solution?
Not sure why your clone() is not working - but try this:
$query = User::where('confirmed', '=', '1');
$query_for_counting_male = $query->replicate();
$query_for_counting_female = $query->replicate();
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_replicate
Since $query is instance of HasMany, So the cloning should be done as:
$query_for_counting_history_books = clone $query->getQuery();
$query_for_counting_geography_books = clone $query->getQuery();
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/HasOneOrMany.html#method_getQuery
I have stored date like this format in db "2014-10-13" from this I need to show records only for the given month in Laravel.
Use mysql Month function
SELECT * FROM tbl_name WHERE MONTH( col_name ) = 3
In laravel:
$name = DB::table('tbl_name')->whereRaw('MONTH(col_name) = 3')->get();
Try this it will work :
SELECT * FROM table_name WHERE MONTH('2014-10-13') = '10';
larval :
$results = DB::select('select * from users where MONTH('2014-10-13') = ?', array(10));
Let me just assume the table names as users and assuming you are using eloquent since you have tagged it under laravel.
This is how you get the users who were created in a particular month.
Eloquent:
$month = 12;// for december
$users = User::whereRaw('MONTH(created_at) = ?',[$month])->get();
return $users;
Query Builder:
$users = DB::table('users')->whereRaw('MONTH(created_at) = ?',[$month])->get();
if you also want to get the month in the results then
Eloquent:
$users = User::select(['*',DB::raw('MONTH(created_at) as month')])
->whereRaw('MONTH(created_at) = ?',[$month])->get();
Query Builder:
$users = DB::table('users')->select(['*',DB::raw('MONTH(created_at) as month')])
->whereRaw('MONTH(created_at) = ?',[$month])->get();