how I delete a row in a table in Joomla? - joomla

I have a table
id h_id t_id
1 3 1
2 3 2
3 3 3
4 4 2
5 4 3
id is the primary key. I have not created a JTable for this table. Now I want to delete rows by h_id. Are there any method like which I can use without writing a sql DELETE query?
$db = JFactory::getDBO();
$row =& $this->getTable('tablename');
$row->delete($pk);
Any better solution will be greatly appreciated.

$db = & JFactory::getDBO();
$query = $db->getQuery(true);
$query->delete($db->nameQuote('tablename'));
$query->where($db->nameQuote('h_id').'='.$db->quote($key));
$db->setQuery($query);
$db->query();

Related

CodeIgniter Group with SUM

I want to learn CodeIgniter, with an example case like this:
I have a database (tbl_points)
And I have an output like this:
id
sku
point
1
001
10
2
001
-1
3
002
5
4
002
-2
5
001
-1
I'm having a hard time making groups based on SKUs and then adding up each value at that point. Can you help me to make it like this? Thank you very much.
id
sku
point
1
001
8
2
002
3
If you want to write query for ci3.
$this->db->select('sku');
$this->db->select_sum('point');
$this->db->from('tbl_points');
$this->db->group_by('sku');
$query = $this->db->get();
$row = $query->result();
print_r($row);
This is resolved with a simple mysql SUM(), see Aggregate Function Descriptions
select * , sum(`point`) as my_point
from `tbl_points`
group by `sku`
in case you really need a new "id", you can extend your query using a User-Defined Variable to add on +1 for each new row:
set #row_num=0;
select * , sum(`point`) as my_point, #row_num:=#row_num+1 AS new_id
from `tbl_points`
group by `sku`
check the corresponding mysql fiddle
create that query with Codeigniter Query Builder
example for CI3.x:
$this->db->select('* , sum(point) as my_point');
$this->db->group_by('sku');
$query = $this->db->get('tbl_points');
and with the User-Defined Variable you need 2 queries, something like:
$sql="set #row_num:=0";
$this->db->query($sql);
$sql="select * , sum(`point`) as my_point, #row_num:=#row_num+1 AS new_id
from `tbl_points`
group by `sku`
";
$query=$this->db->query($sql);
to quickly output the result, you could write this line:
echo '<pre>';print_r($query->result());
anyway recommendable to check How to Generate CI Query Results
You need to sum it first, then group by this fields :-
$sql = "select id,sku, sum(`point`) as my_point from `tbl_points`
group by `sku`";
$query = $this->db->query($sql);
to output the result:-
echo '<pre>';
print_r($query->result());
Your Output result :-
id sku my_point
1 001 8
3 002 3

Counting in many to many relationships just in one column of the pivot table

Many-to-many relationships
table names
table itens
table pivot_itens_names
table pivot_itens_names
id_name | id_item
1 1
2 1
3 8
4 5
I need to count how many times the id_item '1' is in the pivot_itens_names table
expected outcome: $total = 2
This works
$total = DB::select('SELECT COUNT(id_item) AS total
FROM pivot_itens_names WHERE id_item = ?',
[$idItem] );
Intended objective: do the count using eloquent with model
unsuccessful attempt
$idItem = 1;
$data = $Name::itens();
$total = $data->where('id_item', $idItem)->count();
EDITED
One solution is to create a model for the pivot table. I have doubts if this solution is a good practice.
$total = PivotItemName::where('id_item', $idItem)->count();
Add this method to the Name model:
public function items()
{
return $this->belongsToMany('App\Models\Item', 'pivot_items_names')->withPivot('id_item');
}
and then use count method to get count of them

How to select first row record of a specified query in laravel

I want to select one row from the duplicate row result
i have two tables called books and library
Library Table
id name
1 Php
2 laravel
3 react js
4 node js
Books Table
id library_id user_id
1 1 3
2 1 3
3 2 8
4 2 8
5 3 9
so am using join to select the name column from the library table using the library_id as foreign key in the book tables id
i want to select only one row that has the library_id of either 1 or 2 or any book id
Like this
id name library_id
1 php 1
2 laravel 2
3 react js 3
i tried this below but it gives me duplicate rows
$user_id = auth()->user()->id
DB::table('books')
->join('library', 'books.library_id', '=','library.id')
->where('user_id',$user_id))
->distinct('library_id')
->get();
You Can Use
$user_id = auth()->user()->id;
DB::table('books')
->join('library', 'books.library_id', '=','library.id')
->where('user_id','=',$user_id)
->distinct('library_id')
->get();
instead of
DB::table('books')
->join('library', 'books.library_id', '=','library.id')
->where('user_id',$user_id))
->distinct('library_id')
->get();
Try this query:
DB::table('library')
->select('library.id','name')
->whereIn('library.id', function($q) use ($user_id){
$q->from('books')
->select('books.id')
->where('books.user_id',$user_id);
})
->get();

laravel group by fetch latest record from table

I have one table where I want to retrieve data group by the user but I want the latest entry in result how can I do that by using eloquent.
here is an eloquent query I am using.
Product::whereNotNull('user_id')
->orderBy('id','desc')
->groupBy('user_id')
->get();
here is my table
Id Name user_id
-------------------------
1 A 1
2 b 1
3 c 2
4 d 2
5 e 3
6 f 3
result my query is giving me
Id Name user_id
-------------------------
1 A 1
3 c 2
5 e 3
result i want
Id Name user_id
-------------------------
2 b 1
4 d 2
6 f 3
Product::whereRaw('id IN (select MAX(id) FROM products GROUP BY user_id)')
->whereNotNull('user_id')
->orderBy('id','desc')
->get();
You will need a nested query for that, i don't think you can avoid it but this solution should work.
GroupBy happens before OrderBy so you have to get your last record before you do your ordering
Try this :
$subquery = Product::orderBy('id','DESC');
$products = DB::table(DB::raw("({$subquery->toSql()}) as subquery"))
->whereNotNull('user_id')
->groupBy('user_id')
->get();
2nd way : use unique() method in collection (The unique method returns all of the unique models in the collection):
$products = Product::whereNotNull('user_id')
->orderBy('id','desc')
->get()
->unique('user_id');
Check out Laravel Docs
latest / oldest
The latest and oldest methods allow you to easily order results by date. By default, result will be ordered by the created_at column. Or, you may pass the column name that you wish to sort by:
$product = Product::latest()->first();

Laravel 5: how to "order by" using Eloquent ORM form exist to not exist by date

I have a table
id name publish_at total
------------------------
1 shirt1 2000 6
2 shirt2 2019 0
3 shirt3 2010 5
4 shirt4 2019 1
I want sort it by pubish at and not 0 for total in laravel:
I want this:
shirt4
shirt3
shirt1
shirt2
I try this:
$query->orderBy('total', 'desc');
$query->orderBy('publish_at', 'desc');
but it sort by total and for same total sort by publish
you dont need to call the $query again
$query = Model::all()
->orderBy('publish_at', 'ASC')
->get();
return view('view', [
'query ' => $query
]);
Use orderByRaw() :
->orderByRaw(
"order by CASE WHEN total>0 THEN publish_at END DESC, CASE WHEN total>0 THEN total END DESC")

Resources