Home > php教程 > php手册 > orm获取关联表里的属性值 - 微笑女孩

orm获取关联表里的属性值 - 微笑女孩

WBOY
Release: 2016-05-20 11:41:02
Original
971 people have browsed it

ORM——关系对象模型

laravel中的Eloquent ORM用于和数据表互动,其中每个数据库表会和一个对应的「模型」互动,想要了解请查看官方文档或自行百度。获取关联表里的属性值代码如下:

    /**
     * [getContactAttribute 获取卖家联系人]
     */
    public function getContactAttribute()
    {
        return $this->hasOne('App\Http\Models\Supplier', 'SupplierId', 'SupplierId')->first()->contact;
    }
Copy after login

  2、获取订单商品信息

    public function getProductInfoAttribute()
    {
        $info = $this->items()->get()->map(function ($item) {
            $json = $item->format(['title', 'quantity']);//$json为数组
            return implode('x', array_values($json));
        })->toArray();//toArray()将object转换为数组
        if (count($info) > 1) {
            $info = implode(';', $info);
        }else {
            $info = $info[0];
        }
        return $info;
    }

    /**
     * [items 订单购买的商品]
     * @return [type] [description]
     */
    public function items()
    {
        return $this->hasMany('App\Http\Models\OrderItem', 'OrderId', 'OrderId');
    }
Copy after login

  其中getProductInfoAttribute()方法用于获取订单商品的信息,最后效果是:商品1名字x数量;商品2名字x数量。eg:奥力根电链锯x1;金戈铁马台钻x3。

 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template