Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mimic Eloquent relationship with comma separated ids

I have two tables, orders and layers. In my orders table i save an array in layer_id which i have set it to varchar. I explode it first and i display the records. What i wanna do is to display the records from layers table , for example names from layer_name columns . I have also set their relationships . I would appreciate any suggestions.

My controller:

public function getCheckout(){
    $orders = Order::get();
    return View::make('checkout')->with('orders', $orders);
}

My view:

@forelse($orders as $order)

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">{{ $order->style_id }}</h3>
    </div>
    <div class="panel-body">
    <p>Layers you chose</p>

    <table class="table">
        <tr>
        <td>ID</td>
        @foreach(explode(',', $order->layer_id) as $layer) 
            <td>{{ $layer }}</td>
        @endforeach
        </tr>

    </table>
</div>
    <div class="panel-footer"><button class="btn btn-primary">Confirm</button></div>
</div>

@empty

<p>Nothing to display</p>

@endforelse

My Model

Class Order extends Eloquent {
    public function layer() {
        return $this->belongsTo('Layer', 'layer_id');
    }
}
like image 914
Dean Gite Avatar asked Jan 12 '15 09:01

Dean Gite


1 Answers

My first suggestion would be normalize your db. In the context of Eloquent ORM you cannot use built-in relationships for this.

However for the sake of curiosity, here's what you should do:

With below setup you can:

// 1. Use layers like eloquent dynamic property
$order->layers; // collection of Layer models

// 2. Call the query to fetch layers only once
$order->layers; // query and set 'relation'
// ... more code
$order->layers; // no query, accessing relation

// 3. Further query layers like you would with relationship as method:
$order->layers()->where(..)->orderBy(..)->...->get();

// 4. Associate layers manually providing either array or string:
$order->layer_ids = '1,5,15';
$order->layer_ids = [1,5,15];

But you can't:

// 1. Eager/Lazy load the layers for multiple orders
$orders = Order::with('layers')->get(); // WON'T WORK

// 2. Use any of the relationship methods for associating/saving/attaching etc.
$order->layers()->associate(..); // WON'T WORK

But here's what you can do (I suggest renaming layer_id to layer_ids so it is self-explanatory, and my example covers that change):

/**
 * Accessor that mimics Eloquent dynamic property.
 *
 * @return \Illuminate\Database\Eloquent\Collection
 */
public function getLayersAttribute()
{
    if (!$this->relationLoaded('layers')) {
        $layers = Layer::whereIn('id', $this->layer_ids)->get();

        $this->setRelation('layers', $layers);
    }

    return $this->getRelation('layers');
}

/**
 * Access layers relation query.
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function layers()
{
    return Layer::whereIn('id', $this->layer_ids);
}

/**
 * Accessor for layer_ids property.
 *
 * @return array
 */
public function getLayerIdsAttribute($commaSeparatedIds)
{
    return explode(',', $commaSeparatedIds);
}

/**
 * Mutator for layer_ids property.
 *
 * @param  array|string $ids
 * @return void
 */
public function setLayersIdsAttribute($ids)
{
    $this->attributes['layers_ids'] = is_string($ids) ? $ids : implode(',', $ids);
}

edit: Of course you could do simply this in your view. It adheres to your current code, but obviously is far from what I suggest ;)

@foreach (Layer::whereIn('id', explode(',', $order->layer_id))->get() as $layer)
  {{ $layer->whatever }}
like image 157
Jarek Tkaczyk Avatar answered Oct 20 '22 22:10

Jarek Tkaczyk