User picture
By m4rw3r on Oct 12, 2008 @ 10:20am UTC

Re: Is there a better way (one-to-one relations)?

The best option for you is probably to create a wrapper method (or overwriting the find() method in a child class).
This wrapper method should use CI's Active Record methods to include the other columns (technically it will be IgnitedQuery, but who cares?) or use the join_related() method (in your case it should probably be the first option).

Example with your join code:

function &find($id = false)
{
    $this->join_related('metadata')
    ->select('metadata.*')
    ->select('C.name AS createdbyuser')
    ->select('L.name AS lasteditedbyuser')
    ->select('D.name AS deletedbyuser')
    ->join('user C','createdbyid = C.userid','LEFT OUTER')
    ->join('user D','deletedbyid = D.userid','LEFT OUTER')
    ->join('user L','lasteditedbyid = L.userid','LEFT OUTER');

    return parent::find($id);
}


if you don't need the user names of the users who have manipulated the record, the code will be very simple:
function &find($id = false)
{
    $this->join_related('metadata');

    return parent::find($id);
}


But be aware that join_related() prefixes the columns from the metadata table with "metadata_". But in the first function we call select('metadata.*'), which also fetches them without prefixes.

I'll probably need to add a global hook, so people easily can add this kind of functionality to all fetch methods without needing to copy and paste too much.

 

On this conversation: