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 }}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…