I am trying to add a new column total_count that contains the count of all rows in sample for pagination.
Is there a way to select count(*) as total_count in $sample itself instead of $total_count = $sample->count()
$var1 = $request->xyz;
$var2 = $request->abc;
$take = $request->take;
$skip = $request->skip;
$sample = DB::table('table_name')
->where('column_name1', $var1)
->where('column_name2', $var2)
->offset($skip)->limit($take)
->get();
$total_count = $sample->count();
$encrypted = AESEncrypt($sample);
return json_encode($encrypted);
OR can I write something like this
$sample = DB::table('table_name')
->select('table_name.*', DB::raw('COUNT(column_name) as total_count'))
->where('column_name1', $var1)
->where('column_name2', $var2)
->offset($skip)->limit($take)
->get();
You directly call
->paginate(10)
at the end of your query like:
$sample = DB::table('table_name')
->where('column_name1', $var1)
->where('column_name2', $var2)
->paginate(10);
Laravel itself handles all count pages etc.
You can use below code for total count of your table. If you need special where case then you should it too.
ModelName::count();
Or you can use
DB::table('table_name')->count();
You can read more in here
Related
i have query like this, but displays wrong last_message.
$users = Message::join('users', function ($join) {
$join->on('messages.from_id', '=', 'users.id')
->orOn('messages.to_id', '=', 'users.id');
})
->where(function ($q) {
$q->where('messages.from_id', auth()->user()->id)
->orWhere('messages.to_id', auth()->user()->id);
})
->where('users.id','!=',auth()->user()->id)
->select([
'users.id',
'users.name',
'users.avatar',
DB::raw('MAX(messages.created_at) max_created_at'),
DB::raw('MAX(messages.body) last_message'),
DB::raw('CASE WHEN(COUNT(messages.is_read) FILTER (WHERE is_read = false
AND messages.from_id != '.auth()->user()->id.') = 0) THEN true ELSE false END is_read'),
DB::raw('COUNT(messages.is_read) FILTER (WHERE is_read = false
AND messages.from_id != '.auth()->user()->id.') count_unread')
])
->orderBy('max_created_at', 'desc')
->groupBy('users.id')
->paginate($request->per_page ?? 20)
->withQueryString();
when i change
DB::raw('MAX(messages.body) last_message'),
to
DB::raw('messages.body ORDER BY messages.created_at DESC LIMIT 1 last_message'),
display error messages like this, syntax error at or near "last_message". How to fix this?
You want to alias the column, not the statement. Try to change it to:
messages.body last_message ORDER BY messages.created_at DESC LIMIT 1
So you need first order the records based on some column and then return the first record of that list.
$cart_data = ScCart::orderBy('created_at', 'asc')->first();
$cart_data = ScCart::orderBy('created_at', 'desc')->first();
This will work for first and last record created in that table.
i have a joined table like this
i want to create new field named qty_exceed and the value is based from
(qty_stock - qty_taken)
do i have to do it in the query or make separate operation and store it in a varible?
my code
$getmaterial = ContractProduct::select(
'product_item.ref_rof_id',
'product_item.code',
'product_item.qty_stock',
'contract_product.qty_taken'
)
->where('ref_rof_id', $getrof->ref_rof_id)
->join('product_item', 'contract_product.ref_product_id', '=', 'product_item.code')
->get();
$data['getquoid'] = $getquoid;
$data['getmaterial'] = $getmaterial;
$view = $this->module_path . '.next-create';
return response()->view($view, $data);
You need to use DB::raw
But remember, raw statements will be injected into the query as strings, so you should be extremely careful to not create SQL injection vulnerabilities.
With DB::raw your code will look like this:
$getmaterial = ContractProduct::select(
'product_item.ref_rof_id',
'product_item.code',
'product_item.qty_stock',
'contract_product.qty_taken',
ContractProduct::raw('product_item.qty_stock - contract_product.qty_taken as qty_exceed')
)
->where('ref_rof_id', $getrof->ref_rof_id)
->join('product_item', 'contract_product.ref_product_id', '=', 'product_item.code')
->get();
$data['getquoid'] = $getquoid;
$data['getmaterial'] = $getmaterial;
$view = $this->module_path . '.next-create';
return response()->view($view, $data);
I want to make a count by the first letters... I have this column
I would like to count each OE rows and each GICS rows
I'm working with this query
$data4 = DB::table('incidencias')
->select(DB::raw('grupo_asig as grupo_asig'), DB::raw('count(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig')
->orderBy('number', 'desc')
->get();
Use CASE WHEN and count the field like OE and ASIG
$data4 = DB::table('incidencias')
->select(DB::raw("(CASE WHEN grupo_asig LIKE 'OE%' THEN 'OE'
WHEN grupo_asig LIKE 'GICS%' THEN 'GICS'
END) AS grupo_asig_type"),
DB::raw('COUNT(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig_type')
->orderBy('number', 'desc')
->get();
You should try to use the [LIKE][1] function then and add it to your query:
->where('grupo_asig', 'like', 'OE%')
->where('grupo_asig', 'like', 'GICS%')
Edit:
I tried a lot around and came to this solution and made a SQL fiddle: http://sqlfiddle.com/#!9/06a39b/8
Does it help you?
You could use Collections. No real need to change your query much.
$data4 = DB::table('incidencias')
->select('grupo_asig')
->selectRaw('count(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig')
// ->orderBy('number', 'desc') Unless you use this array somewhere, it's not needed.
->get();
use Illuminate\Support\Str;
...
// php >= 7.4.0
$oe_count = $data4->filter(fn($data) => Str::startsWith($data->grupo, 'OE '))->count();
$gigs_count = $data4->filter(fn($data) => Str::startsWith($data->grupo, 'GIGS '))->count();
// php < 7.4.0
$oe_count = $data4->filter(function ($data) {
return Str::startsWith($data->grupo, 'OE ');
})->count();
$gigs_count = $data4->filter(function ($data) {
return Str::startsWith($data->grupo, 'GIGS ');
})->count();
Starting with Laravel 6, you can also use cursor() instead of get() in your query to return a LazyCollection. It's faster for this scenario.
I would suggest using a query for that:
refer to this answer
SELECT
LEFT(grupo_asig, 1) AS first_letter,
COUNT(*) AS total
FROM incidencias
GROUP BY first_letter
I have an Entity "Company" (linked to an "Account") which can have multiple "Tickets".
I want to get the five first companies with the most tickets
I've got this so far but it doesn't work :
public function getByMostTickets($idAccount) {
$qb = $this->createQueryBuilder('c')
->where("c.account = ".$idAccount)
->orderBy("COUNT(c.tickets)", "DESC");
return $qb->getQuery()->getResult();
}
Apparently, it doesn't like that I do the "COUNT" in the orderBy.
Can you try something like this?
$qb = $this->createQueryBuilder('c')
->join("c.tickets", "t")
->where("c.account = :account_id")
->setParameter("account_id", $idAccount)
->groupBy("c.id")
->orderBy("COUNT(t.id)", "DESC");
[EDITED]
sorry this should work... But dump the result to see what this returns...
$qb = $this->createQueryBuilder('c')
->select("c", "COUNT(t.id) as countTickets")
->join("c.tickets", "t")
->where("c.account = :account_id")
->setParameter("account_id", $idAccount)
->groupBy("c.id")
->orderBy("countTickets", "DESC");
I am new to zend framework,
Following is the plain mysql query which takes particular column from table,
SELECT jobs_users.id,jobs_users.first_name from jobs_users left join friends on jobs_users.id=friends.friend_id where friends.member_id=29
I tried with zend to implement the above query like below,
public function getFriendsProfileList($id){
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('jobs_users')
->joinLeft(
'friends',
'jobs_users.id=friends.friend_id',
array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo')
)
->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;
}
Here i got result with all column name , not with exact column name which i have given in query.
Kindly help me on this.
Use this instead:
$select->from('jobs_users', array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'))
->joinLeft('friends', 'jobs_users.id=friends.friend_id')
->where("friends.member_id = ?", '20');
You may also try this:
$select = $db->select();
$select->setIntegrityCheck(false);
$select->joinLeft('jobs_users','',array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'));
$select->joinLeft('friends','jobs_users.id=friends.friend_id', array());
$select->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;