Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new to building databases and I'm trying to do a JOIN based on a having three database tables.

Table A = ID, Name, etc
Table B = ID, Name, etc
Table C = ID, TableAId, TableBId

What I can't figure out is using active record how to make this selection. I'm trying to make as few requests as possible, but am getting stumped on how it should all be written without doing three separate calls.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

$this->db->select('*');
$this->db->from('TableA AS A');// I use aliasing make joins easier
$this->db->join('TableC AS C', 'A.ID = C.TableAId', 'INNER');
$this->db->join('TableB AS B', 'B.ID = C.TableBId', 'INNER');
$result = $this->db->get();

The join function works like this: join('TableName', 'ON condition', 'Type of join');

The equivilent sql:

SELECT *
FROM TableA AS A
    INNER JOIN TableC AS C
    ON C.TableAId = A.ID
    INNER JOIN TableB AS B
    ON B.ID = C.ID

I found that writing the SQL first, testing it, then converting to the active record style minimizes error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...