Lithium with left join - sql

I'm new with Lithium.I need to do a left join.This is the query I need.
SELECT `title`,`body`,`user_id`,`users`.`username`,`users`.`id`
FROM `posts` LEFT JOIN `users`
ON `user_id` = `users`.`id`
I try to do something like this.
$conditions['user_id'] = $this->data['user_id'];
$posts = Post::all(array(
'conditions' => $conditions,
'fields' => array('title','body','username'),
'join' => array('source' => 'posts',
'type' => 'LEFT',
'constraint' => array('post.user_id' => 'Users.id')),
))->data();

There is a great tutorial (using a blog as an example) here which explains using Relationships in Lithium, Relationships make using relational data and JOINS simpler.
You can also check out the official docs as well as this answer: How do I perform joins with lithium models?
Once you have your Relationships set on your Models you can do your JOINS as simply as:
$posts = Posts::find('all', array(
'with' => 'Users'
));
There are a couple differant types of Relationships in Lithium, which roughly corrspond to differant types of JOINS ...
hasOne: the current object is linked to a single object of another type
hasMany: the current object is linked to many objects of another type
belongsTo: the current object is owned and marked as related to
another object

Related

How do you add join a table using Criteria in yii for CActiveDataProvider?

I have three tables in my db tbl_project, tbl_employee and tbl_user_assignment.
I need to write CDbCriteria on below sql query
SELECT * from tbl_project
INNER JOIN tbl_user_assignment
ON tbl_user_assignment.project_id = tbl_project.id;
JOIN tbl_employee
ON tbl_employee.id = tbl_user_assignment.user_id
WHERE tbl_employee = 8
i have already created model class for these three tables as Project,Employee,Userassign respectively.
my data provider code is
$dataProvider=new CActiveDataProvider('Project',array(
'pagination'=>array(
'pageSize'=>3,
),
));
Please help
Thanks
You need to add a criteria which contains a with. Use the relationship name(s) you've defined in your models.
$dataProvider=new CActiveDataProvider('Project',array(
'pagination'=>array(
'pageSize'=>3,
'criteria'=>array(
'with'=>array(
'userassign',
'employee',
)
)
));
You'll obviously need to change the above to match your personally requirements.
More about criteria on the yii forum

Ruby on Rails: Select from database where column equals a value from array

If I have an array of IDs from a table (table1) in my database. Is there a way of querying another table (table2) to select all the records where a column equals a value equal to one of the IDs from table1.
My code so far is:
LabQuestion.where("product_id=#{Product.where(:brand_id => brand_id).pluck(:id)}")
In this code, I am trying to retrieve all the Lab Questions which are linked to all the products from a brand. This code does not work, but I've tried to demonstrate my needs.
Assuming you have setup your relations properly, you can use joins to join the two tables and query them like this:
LabQuestion.joins(:product).where(:products => { :brand_id => brand_id })
You can use includes instead of joins as below
LabQuestion.includes(:product).where(:products => { :brand_id => brand_id })

NHibernate.QueryException: not an association: Id

I wrote a joint query using NHiberNate, but I am getting a NHibernate.QueryException:not an association: Id
This is what it looks like with NHibernate library
TicketRequest ticketAlias = null;
Show showAlias = null;
IList<TicketRequest> results = UnitOfWork.CurrentSession.QueryOver<TicketRequest>(() => ticketAlias)
.JoinAlias(() => ticketAlias.ShowId, () => showAlias.Id)
.Where(() => showAlias.ShowDate >=DateTime.Now)
.List();
return results;
I just want a simple joint statement, and this is what it would have been in SQL
select * from TicketRequest as a join Show as b
on a.Show_id = b.Id
where ShowDate >=GETDATE()
Can someone help and let me know why I am getting a "not an association:Id" error. I have id in the "Show" table, it is a primary key.
Please advise. All helps are greatly appreciated.
You need to specify a many-to-one relation in joins. In your case that is the Show property.
IList<TicketRequest> results = UnitOfWork.CurrentSession.QueryOver<TicketRequest>(() => ticketAlias)
.JoinAlias(() => ticketAlias.Show, () => showAlias)
.Where(() => showAlias.ShowDate >= DateTime.Now)
.List();
PS: You shouldn't map both a many-to-one relation (Show) and an foreign key property (ShowID). Usually you only work with object relations when using an ORM. Only map the plain ID if you really need it for something, but even then only map it as read-only.
You don't have to specify the foreign keys / primary keys when querying with NHibernate. It's an ORM. You write object oriented queries. The keys and relations are specified in the mapping file.
A Join in an NHibernate query is simply specified by the property name with which you navigate to the other property.
That's what the error message means. Id is not an association.

Selecting from multiple tables with Yii's CActiveDataProvider

I have 3 tables: Topics, Users and Details (those are some of the tables of a custom forum)
Topics contains (among other usual fields) the id (FK) of the user that created the topic.
Users contains nick/pass and id (PK)
Details contains (among other usual fields) the id (FK) of the user.
Relations:
One user can have one 1 detail.
One user can have multiple topics, but a topic can be created only by one user.
Topic relations:
return array(
'user' => array(self::BELONGS_TO, 'User', 'User_iduser'),
);
User relations:
return array(
'details' => array(self::HAS_ONE, 'Details', 'User_iduser'),
);
I'm trying to get a list with Topics and User details (let's say for example the topic name and the user's name).
Currently I have this:
$dataProvider=new CActiveDataProvider('Topic', array(
'criteria'=>array(
'with'=>array('user.details')
)
));
But as you can imagine, it's not working (read as in it's not selecting anything from the tbles Users or Details).
What's wrong with my code?
+++++++++++++++
This code selects fields from the table user (and the topic table):
Topic::model()->with('user')->findAll();
But this one won't select from details, users and topic:
Topic::model()->with('user.details')->findAll();
Also, I need a CActiveDataProvider solution as I need it for zii widgets (means, even if some kind of modification on the Topic::model()->with().... code get's to select from the 3 tables it won't be really helpful)
EDIT: (SQL log from Yii)
Querying SQL: SELECT COUNT(DISTINCT `t`.`idtema`) FROM `tema` `t` LEFT
OUTER JOIN `usuario` `usuarioIdusuario` ON
(`t`.`Usuario_idusuario`=`usuarioIdusuario`.`idusuario`) LEFT OUTER JOIN
`detallesusuario` `detallesusuario` ON
(`detallesusuario`.`Usuario_idusuario`=`usuarioIdusuario`.`idusuario`)
Querying SQL: SELECT `t`.`idtema` AS `t0_c0`, `t`.`Usuario_idusuario` AS
`t0_c1`, `t`.`Categoria_idcategoria` AS `t0_c2`, `t`.`tema` AS `t0_c3`,
`t`.`fecha_hora` AS `t0_c4`, `usuarioIdusuario`.`idusuario` AS `t1_c0`,
`usuarioIdusuario`.`nick` AS `t1_c1`, `usuarioIdusuario`.`contrasena` AS
`t1_c2`, `usuarioIdusuario`.`email` AS `t1_c3`,
`detallesusuario`.`Usuario_idusuario` AS `t2_c0`,
`detallesusuario`.`nombre` AS `t2_c1`, `detallesusuario`.`apellidos` AS
`t2_c2`, `detallesusuario`.`cumpleanos` AS `t2_c3`,
`detallesusuario`.`telefono1` AS `t2_c4`, `detallesusuario`.`telefono2` AS
`t2_c5` FROM `tema` `t` LEFT OUTER JOIN `usuario` `usuarioIdusuario` ON
(`t`.`Usuario_idusuario`=`usuarioIdusuario`.`idusuario`) LEFT OUTER JOIN
`detallesusuario` `detallesusuario` ON
(`detallesusuario`.`Usuario_idusuario`=`usuarioIdusuario`.`idusuario`)
LIMIT 10
Try this
$dataProvider=new CActiveDataProvider('Topic', array(
'criteria'=>array(
'with'=>array('user'=>array('alias'=>'user','with'=>array('details'=>array('alias'=>'details'))))
)
));
And
Topic::model()->with(array('user'=>array('alias'=>'user','with'=>array('details'=>array('alias'=>'details')))))->findAll();
instead of the line
'with'=>array('user.details')
use
'with'=>array('user')
then add
$criteria->compare( 'user.details', $query, true );
$criteria->together = true;
}
*Where $query is a variable that will be searched in column details

Find records with more than one ActiveRecord HABTM Association

I've got two models, joined by a Has and Belongs To Many join table. Lets call these models User and Event. The majority of Users have 0 events, while few have one or more. I want to do something like:
User.find(:all, :joins => :events, :conditions => ["'Something that count the events' > ?"], 0)
The problem is, I'm not sure how to select only users that have 1 or more associated events.
I've found the answer:
User.find(:all, :joins => :events, :select => 'DISTINCT `users`.*')
Basically, the users.* restricts the result set to just the users table, and the DISTINCT keyword makes sure each user is only returned once.