laravel 如何用逗号分隔的 id 模仿 Eloquent 关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27898953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:40:41  来源:igfitidea点击:

How to mimic Eloquent relationship with comma separated ids

databaselaraveleloquent

提问by Dean Gite

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.

我有两个表,订单和图层。在我的订单表中,我在 layer_id 中保存了一个数组,我已将其设置为 varchar。我先爆炸它,然后显示记录。我想要做的是显示来自图层表的记录,例如来自 layer_name 列的名称。我也设定了他们的关系。我将不胜感激任何建议。

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');
    }
}

回答by Jarek Tkaczyk

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

我的第一个建议是规范化你的 db。在 Eloquent ORM 的上下文中,您不能为此使用内置关系。

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_idto layer_idsso it is self-explanatory, and my example covers that change):

但这是您可以执行的操作(我建议重命名layer_id为,layer_ids以便不言自明,我的示例涵盖了该更改):

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

回答by Jonas Staudenmeir

I created a package that allows you to define many-to-many relationships using JSON arrays:
https://github.com/staudenmeir/eloquent-json-relations

我创建了一个包,允许您使用 JSON 数组定义多对多关系:https:
//github.com/staudenmeir/eloquent-json-relations

You can use it like this:

你可以这样使用它:

class Order extends Model {
    use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

    protected $casts = [
        'layer_id' => 'json',
    ];

    public function layers() {
        return $this->belongsToJson(Layer::class, 'layer_id');
    }
}

class Layer extends Model {
    use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

    public function orders() {
        return $this->hasManyJson(Order::class, 'layer_id');
    }
}