Skip to content
This repository has been archived by the owner on Dec 9, 2022. It is now read-only.

3. Model Associations with Linkable

Sykam Raju edited this page Apr 24, 2014 · 2 revisions

Lets expand on Example 3 from the Basic Usage tutorial by adding in some associated data using the Linkable Behavior. The Linkable Behavior handles querying the database for 1-to-1 relations such as hasOne and belongsTo much more efficiently than Containable (which will be handled in another tutorial). Linkable will not work with 1-to-many relations such as hasMany.

In the example below want to display a users group and location data.

$this->paginate  = array(
    'link' => array(
        'User',
        'UserGroup',
        'UserLocation'
    'order' => 'User.id DESC',
    'group' => 'User.id'
)
);

Our HTML:

<table id="users-table">
    <thead>
        <th>Username</th>
        <th>Group</th>
        <th>Location</th>
        <th>Email</th>
        <th>Created</th>
    </thead>
    <tbody>
    </tbody>
</table>

In our JavaScript we'll go ahead and create a link to users/view, user_groups/view, and user_locations/view.

$('#users-table').dataTable({
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "/users/index.json",
    "sDom": "fr",
    "iDisplayLength": 20,
    "aoColumns": [
        {mData:"User.username"},
        {mData:"UserGroup.name"},
        {mData:"UserLocation.name"},
        {mData:"User.email", bSortable: false},
        {mData:"User.created", bSearchable: false}
    ],
    "fnCreatedRow": function(nRow, aData, iDataIndex){
        $('td:eq(0)', nRow).html('<a href="/users/view/'+aData.User.id+'">'+aData.User.username+'</a>');
        $('td:eq(1)', nRow).html('<a href="/user_groups/view/'+aData.UserGroup.id+'">'+aData.UserGroup.name+'</a>');
        $('td:eq(2)', nRow).html('<a href="/user_locations/view/'+aData.UserLocation.id+'">'+aData.UserLocation.name+'</a>');
    }
});
Clone this wiki locally