【问题标题】:Laravel Model function to get related entities description as stringLaravel 模型函数以字符串形式获取相关实体描述
【发布时间】:2019-07-22 08:16:57
【问题描述】:

我有两个实体关系,其中 Order hasMany OrderItems。我正在尝试在我的 desc 函数中获取订单商品详细信息作为描述字符串,如下所示。

class Order extends Model
{
    public function items(){
        return $this->hasMany(OrderItem::class);
    }

    public function desc() : string
    {
      $items = $this->items->select("item_name, price")->get();   
      $desc='';
      foreach($items as $item){
        $desc .=implode(':',$item).', ';
      }
      return $desc;
      //return 'item_name:price, cards:50,'
    }  
}

它的投掷

“implode(): 传递的参数无效”

你能帮我吗,我怎么能做到这一点?有没有更好的方法来做到这一点?

【问题讨论】:

  • @Indra toString 正在抛出错误
  • $this->items 返回一个集合。查看手册中可用的方法,找到您需要的方法
  • or this->items->each(functiond($index, $value) { // 返回你的逻辑 });

标签: php laravel eloquent


【解决方案1】:

在您的 OrderItem 模型中使用它

public functon getDescAttribute()
{
    $value = "{$this->item_name}:{$this->price}";
    return $value;
}

这一定是最好的解决方案,$item->desc 来检索它

【讨论】:

    【解决方案2】:

    解决方案可以是访问器:在模型中使用 get...Attribute():

    public function getOrderItemDetailsAttribute() {
        $details= new Collection();
        foreach ($this->items as $item) {
            $details= $details->add('name: '.$item->item_name.' ; price: '.$item->price);
        }
    
        return $details;
    }
    

    通过以下方式调用:

    order->orderItemDetails;
    

    【讨论】:

    【解决方案3】:

    我确定这不是最好的解决方案,但您可以尝试:

    public function desc() : string
    {
          $items = $this->items
               ->select("item_name, price")
               ->pluck("item_name, price")
               ->all(); // here you get array with key-value pairs
    
          $desc = '';
          foreach ($items as $k => $v) {
            $desc .= 'item_name: ' . $k . ', price: ' . $v . ',';
          }
          return $desc;
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2014-05-23
      • 2011-08-22
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      相关资源
      最近更新 更多