Reputation: 435
I have 2 tables
Users Table => id , username
OrdersTable => order_id,user_id, qty,total
I need to link these two tables with .
id and user_id.
how can i do this with grocery CRUD.
Upvotes: 0
Views: 4675
Reputation: 26477
If you're using OrdersTable
as your primary table, you can use a 1:1
relationship using set_relation(). This would be if you were viewing an order and wanted to see/set which user the order belongs to.
$crud->set_table('OrdersTable');
$crud->set_relation('id','UsersTable','username');
This will allow you to select which user for a particular order.
However, presumably a user may have many orders- a 1:n
relationship. This would be the case if UsersTable is your primary table, i.e. you're viewing a user
in the CRUD and want to see all associated orders.
This method requires an intermediary table, with which you link the two existing tables, and a slight change to your existing table structure. You'd need to remove user_id
in the OrdersTable
. The intermediary table, for the sake of argument called UserOrdersTable
would require the following columns.
user_id INT
order_id INT
priority INT
You can then add the relationship using the set_relation_n_n() method.
You can then reverse the set_relation_n_n()
call for when viewing the OrdersTable
so you can see which user made an order.
To summarise, a 1:n
relationship using set_relation_n_n()
will allow you to view orders by a user, and a user for an order.
Upvotes: 3
Reputation: 100175
If you mean query, then;
select u.id, u.username, o.order_id, o.qty, o.total from users u left join orders o on(o.user_id = u.id) where 1=1
Upvotes: -1