[eluser]Onema[/eluser]
I have been using the CI ORM, and I really like it, but I'm having a hard time trying to figure out how to do a search using a 1:1 relationship.
I have a site that works as a directory of people. therefore the information about users of the sites is split into 'user' information and 'contact' information. Only users that log in to the site can have a user and contact, but a contact doesn't have to have a user.
Code:
-- -----------------------------------------------------
-- Table `contact`, I have omitted FK for simplicity
-- -----------------------------------------------------
DROP TABLE IF EXISTS `contact` ;
CREATE TABLE IF NOT EXISTS `contact` (
`id` INT NOT NULL AUTO_INCREMENT ,
`first_name` VARCHAR(255) NULL ,
`last_name` VARCHAR(255) NULL ,
`phone_number` VARCHAR(45) NULL ,
`email_address` VARCHAR(255) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;
-- -----------------------------------------------------
-- Table `user`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `user` ;
CREATE TABLE IF NOT EXISTS `user` (
`id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(255) NOT NULL ,
`password` VARCHAR(32) NULL ,
`contact_id` INT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `username_UNIQUE` (`username` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;
models look like this
Code:
class User extends DataMapper {
public $has_one = array(
'Contact' => array(
'class' => 'Contact'
)
);
}
class Contact extends DataMapper {
}
What i'm trying to do is to search based on a keyword on the username or first_name or last_name something like this:
SELECT user.*, contact.*
FROM user
LEFT JOIN contact
ON contact.id = user.contact_id
WHERE username LIKE '%keyword%'
OR first_name LIKE '%keyword%'
OR last_name LIKE '%keyword%';
and this is how I'm trying to implement it, although it is wrong
Code:
$search_string = $search_string;
$User = new User();
$User->or_like('username', $search_string);
$User->or_like_related('Contact', 'first_name', $search_string);
$User->or_like_related('Contact', 'last_name', $search_string);
$users = $User->get();
I keep getting this error message
A Database Error Occurred
Error Number: 1146</p><p>Table 'contact_user' doesn't exist</p><p>SELECT `user`.*
FROM (`user`)
LEFT OUTER JOIN `contact_user` contact_contact_user ON `user`.`id` = `contact_contact_user`.`_id`
LEFT OUTER JOIN `contact` contact_contact ON `contact_contact`.`id` = `contact_contact_user`.`_id`
WHERE `user`.`username` LIKE '%user%'
OR `contact_contact`.`first_name` LIKE '%user%'
OR `contact_contact`.`last_name` LIKE '%user%'</p>
That query looks very messed up and I don't know why
any ideas?
Thank you.