[英]Count number of rown against each id in other table contains the same id as foreign key using active records
I have the fowllowing two tables from where i need complete list of Racks and count the no of foreign keys rack_id matches with the rack.id and id of racks not matched with any of the rack_id it should retun 0 我有下面两张桌子,在这里我需要完整的机架列表,并计算与机架.id和机架ID匹配的外键编号,机架ID与应与机架ID匹配的机架不匹配0
Modal 语气
function getRacksList()
{
$this->db->select('rack.name as name, rack.details as details, rack.id as id');
$this->db->from('books');
$this->db->join('rack', 'rack.id = books.rack_id', 'left');
$query = $this->db->get();
return $query->result();
}
Controller
function rackDetails(){
$data['racks'] = $this->rack_model->getRacksList();
print_r($data['racks']);
die();
}
Results i am getting 我得到的结果
Array ( [0] => stdClass Object ( [name] => Software Engineering [details] => This Book Rack is for Software Engineering Books [id] => 1 )
[1] => stdClass Object ( [name] => Computer Sciences [details] => This rack is for Computer Sciences Books [id] => 2 )
[2] => stdClass Object ( [name] => Software Engineering [details] => This Book Rack is for Software Engineering Books [id] => 1 )
[3] => stdClass Object ( [name] => Software Engineering [details] => This Book Rack is for Software Engineering Books [id] => 1 )
)
Racks 架
id rack_name
1 rack one
2 rack two
3 rack three
4 rack four
5 rack five
Books 图书
id book_name rack_id
1 book one 1
2 book two 1
3 book three 2
4 book four 2
5 book five 3
If I followed you correctly, a solution would be to LEFT JOIN
the rack
table with th books
table and use aggregation to count how many books belong to each rack. 如果我正确地遵循了您的要求,一种解决方案是将rack
表与rack
表一起LEFT JOIN
books
表,并使用聚合来计算每个书架中有多少书。
Here is a code snippet that uses raw sql : 这是一个使用原始sql的代码片段:
function getRacksList()
{
$query = $this->db->query("
SELECT rack.name, rack.details, rack.id, COUNT(books.rack_id) as books_count
FROM rack
LEFT JOIN books ON rack.id = books.rack_id
GROUP BY rack.name, rack.details, rack.id
");
return $query->result();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.