I want to implement a Join on Same entity 2 times on 2 different associated fields with 2 tables.
but it seems addJoinedEntityFromClassMetadata () Does not support it?
For e.g. I want to specify same Entity class parameter 2 times with different alias.
addJoinedEntityFromClassMetadata("Entity\User","u1".....) and addJoinedEntityFromClassMetadata("Entity\User","u2".....) and
Please suggest if it is supported.
of course it's supported .
You have to set different aliases to your entities, et specify aliases for duplicated column like this :
addJoinedEntityFromClassMetadata('Entity\User', 'user1', OKey, array ( 'id' => 'user1id' ));
addJoinedEntityFromClassMetadata('Entity\User', 'user2', OKey, array ( 'id' => 'user2id' ));
* Okey is the name of the relationship column on your root entity
Related
I have three tables whose structure is is similar to below :
employees offices postings
________ ________ ___________
id id employees_id
name name offices_id
So I want to know how can I get the office name from Employee model. Putting office within $hasOne array shows Unknown column 'office.employees_id' in 'on clause'. What should I do to get the office name in the results ?
If you want to stick to your database, you might use has and belongs to many relation.
In employee.php:
public $hasAndBelongsToMany = [
'Office'=> [
'foreign_key' => 'employees_id',
'joinTable' => 'postings',
'associationForeignKey' => 'offices_id',
]
];
Then you can get office from employee model.
What I really want to suggest is that put a column office_id in employees table, and put
$public $belongsTo = ['office'];
in your employee model.
PS: Brackets [] is supported in php 5.4 or newer , if you are using php 5.3 or lower, you may want to replace it with array().
By example:
r = Model.arel_table
s = SomeOtherModel.arel_table
Model.select(r[:id], s[:othercolumn].as('othercolumn')).
joins(:someothermodel)
Will product the sql:
`SELECT `model`.`id`, `someothermodel`.`othercolumn` AS othercolumn FROM `model` INNER JOIN `someothermodel` ON `model`.`id` = `someothermodel`.`model_id`
Which is correct. However, when the models are loaded, the attribute othercolumn is ignored because it is not an attribute of Model.
It's similar to eager loading and includes, but I don't want all columns, only the one specified so include is no good.
There must be an easy way of getting columns from other models? I'd preferably have the items return as instances of Model than simple arrays/hashes
When you do a select with joins or includes, you will be returned an ActiveRecordRelation. This ActiveRecordRelation is composed of only the objects of the class which you use to call select on. The selected columns from the joined models are added to the objects returned. Because these attributes are not Model's attribute they don't show up when you inspect these objects, and I believe this is the primary reason for confusion.
You could try this out in your rails console:
> result = Model.select(r[:id], s[:othercolumn].as('othercolumn')).joins(:someothermodel)
=> #<ActiveRecord::Relation [#<Model id: 1>]>
# "othercolumn" is not shown in the result but doing the following will yield correct result
> result.first.othercolumn
=> "myothercolumnvalue"
I have three tables as follows
user(username address)
profile(fname,lname,mobile)
details(performance,activity)
I want all information from the above three tables in one query
i.e. I want to make join of three tables for one common id field
I have the following query which retrives only two table fields
#details=User.find(:all,:joins => :profile,:select => "*")
How to do it for all three tables ???
Here's how this query would look:
#details = User.select('*').joins(:profile, :details).all
I'm not convinced this is actually a good way to do anything, but it should work.
This worked for me:
value_variable = 'hello world'
Member.joins(:person => [:workplace => [:business]]).where("businesses.name LIKE :value", value: "%#{value_variable}%")
NOTE: Tested on rails 3.2, 4.x, 5.x
Sorry to ask all these questions about Kohana. They usually get ignored. I think I just found a bug. I'm making a join between two tables that are not directly related.
$results = ORM::factory('foo')->join("bar")->on("foo.foreign_id", "=", "bar.id");
This generates a query that does not resolve the table names explicitly:
SELECT * FROM `foo` JOIN `bar` ON (`foo`.`foreign_id` = `bar`.`id`)
Which gives (in phpMyAdmin) a table that looks like this:
id time foreign_id blah_int id baz
4 1291851245 3 0 3 52501504
Notice there are two id columns, one for the foo table and one for bar. This is a real problem. Because now, in my results, if I loop through...
foreach ($results as $result) {
echo $result->id; // prints 3!!!
}
Because my results should be foo objects, I expect to get an id of 4, but it's giving me 3 because of the join. Is this a bug in the ORM library? Should I be using a different method to restrict my results from the query? I really don't want to do two separate queries where I load all the bars id's, and then load my foos that way, but it looks like I have to.
You have to use the Database object to build raw queries, not ORM, like this:
$results = DB::select()->from('foo')->join('bar')->on("foo.foreign_id", "=", "bar.id")->execute();
You will need to specific some column aliases however to make your query work unless you use ORM as it was intended.
Using ORM
If you want to use ORM, you need to define the relationships in your model. You mention that they share a relationship with another table so in your case you could use a has many through relationship like this:
protected $_has_many = array(
'bars' => array('model' => 'bar', 'through' => 'other_table', 'foreign_key' => 'foreign_id'),
);
Although your example as given suggests that a straight has_many relationship would work:
protected $_has_many = array(
'bars' => array('model' => 'bar','foreign_key' => 'foreign_id'),
);
This would allow you to access all of the bars using a statement like
$bars = $results->bars->find_all();
foreach($bars as $bar)
{
echo $bar->id; // should echo 4, assuming one record in bars with id 4
}
The Kohana 3.1 ORM Reference Guide is good place to start if you want to learn more about ORM and relationships
Using the Kohana database object and query builder
If you prefer ad hoc queries and are doing joins using the query builder you will likely have colliding column names regardless if you are using Kohana or just raw queries (pop "SELECT * FROM foo JOIN bar ON (foo.foreign_id = bar.id)" into MySQL and you will get the exact same result).
Kohana, just like MySQL allows you to define column aliases for precisely this reason. (See here for more information)
Rewrite your query as follows:
$results = DB::select('id', 'time', 'foreign_id', array('bar.id', 'bar_id'), 'baz')->from('foo')->join("bar")->on("foo.foreign_id", "=", "bar.id")->execute();
This will return:
id time foreign_id blah_int bar_id baz
4 1291851245 3 0 3 52501504
I cant get rails to return combined ('AND') searches on associated join tables of an Object.
E.g. I have Books that are in Categories. Lets say: Book 1: is in category 5 and 8
But I can't get 'AND' to filter results using the join table? E.g ::->
Class Books
has_and_belongs_to_many :categories, :join_table => "book_categories"
Book.find :all, :conditions => "book_categories.category_id = 5 AND book_categories.category_id = 8", :include => "categories"
... returns nil
(why does it not return all books that are in both 5 & 8 ??)
However: 'OR' does work:
Book.find :all, :conditions => "book_categories.category_id = 5 OR book_categories.category_id = 8"
... returns all books in category 5 and 8
I must be missing something?
The problem is at the SQL level. That condition runs on a link table row, and any individual link table row can never have a category_id of both 5 and 8. You really want separate link table rows to have these IDs.
Try looking into Rails' named_scope, specifically the part that allows filtering with a lambda (so you can take an argument). I've never tried it out myself, but if I had to implement what you're looking for, that's what I'd look in to.