Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

database - 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');
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 IlluminateDatabaseEloquentCollection
 */
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 IlluminateDatabaseEloquentBuilder
 */
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 }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...