Reputation: 149
i need some codeigniter 3 help from you friends. its like 10 years ago when i did some more complex querys and my noobish JOIN-trys just gave me errors and questionmarks for hours.
lets say i have a mysql table covers
id, text, bgcolor_id, color_id
example : 1, "nice headline", 55, 88
and a table colors
id, value, name
example : 55, #FF0000, "red"
example : 88, #000000, "black"
how to "link" based on bgcolor_id, color_id in table covers
cover.bgcolor_id ->
color.value AS bgcolorvalue
color.name AS bgcolorname
cover.color_id ->
color.value AS colorvalue
color.name AS colorname
my codeigniter model
public function list(){
$query = $this->db->query('SELECT * FROM covers ORDER BY id DESC');
return $query->result_array();
}
public function get($id){
$query = $this->db->query('SELECT * FROM covers WHERE id = ' . $id);
return $query->row();
}
Upvotes: 0
Views: 2515
Reputation: 6282
As i have understood your question right then you want to join on colors
table twice for bgcolor_id
and color_id
, so here i am providing solution for your question let me know if it works or something wrong with the solutuion, thanks.
public function list(){
$query = $this->db->select("covers.*, bg.value AS bgcolorvalue bg.name AS
bgcolorname, colors.value AS colorvalue
colors.name AS colorname")
->join("colors", "colors.id = covers.color_id", "left")
->join("colors as bg", "bg.id = covers.bgcolor_id", "left")
->get("covers")->result();
return $query->result_array();
}
Upvotes: 0
Reputation: 875
I strongly recommend you to use the query builder Reference
You could to something like.
$cv = 'covers';
$cl1 = 'colors';
$cl2 = 'colors';
$get = array(
$cv.'.id',
$cv.'.text',
$cv.'.bgcolor_id',
$cv.'.color_id',
$cl1.'.value as bgcolorvalue',
$cl1.'.name as bgcolorname',
$cl1.'.value as colorvalue',
$cl1.'.name as colorname'
);
$this->db->select($get);
$this->db->from($cv);
$this->db->where($cv.'.id', 1);
$this->db->join($cl1, $cv.'.bgcolor_id = ' . $cl1.'.id');
$this->db->join($cl2, $cv.'.color_id = ' . $cl2.'.id');
$result = $this->db->get()->result();
let me know if this works
Upvotes: 0
Reputation: 64496
Join twice your colors table
select c.*,c1.name bgcolorname,
c1.value bgcolorvalue,
c2.name colorname,
c2.value colorvalue
from covers c
join colors c1 on c.bgcolor_id = c1.id
join colors c2 on c.color_id = c2.id
Upvotes: 3