-1

Using Codeigniter and Datamapper: I have 2 tables: tags and clients. Clients can have many tags, tags can have many clients. I am using a separate join table to save the relationships.

I have a page for managing an individual tag, where I am iterating through every client, and want to check if each one is related to this tag.

The ???? in the code below determines if the checkbox is checked, it should be TRUE if the client has the tag, FALSE if not.

<h2>Manage Tag: <?php echo $tag->name; ?></h2>

<?php foreach ($clients as $client): ?>

    <label>
        <?php echo form_checkbox('client_id[]', $client->id, ????); ?>
        <?php echo $client->name; ?>
    </label>

<?php endforeach; ?>

How can I check if $client is related to $tag in this loop with Datamapper?

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228

1 Answers1

2

How about

$client->is_related_to($tag)

or

$client->is_related_to('tag', $tag->id)

See http://datamapper.wanwizard.eu/pages/count.html#is_related_to

Note that this will fire additional count() queries, you might be better of fetching $tag->clients, and then check in your loop if

isset($tag->clients->all[$client->id])
WanWizard
  • 2,574
  • 15
  • 13
  • Per your edit: I could not get the second solution did to work, would I need to enable `all_array_uses_ids` or something? My original workaround was looping once through `$tag->client`, throwing the client ids in an array, and then using `in_array($client->id, $related_tag_ids)` which produces no (or less) extra queries. I'll have to take a look at the generated queries and see what is happening. Sometimes efficiency is better than elegance. – Wesley Murch Aug 01 '11 at 21:20
  • Bit late, but yes, you need 'all_array_uses_ids'. I have that default in every application, so I forgot to mention that, sorry... – WanWizard Apr 25 '12 at 20:13