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

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

May 20, 2016 am 11:41 AM

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。

 

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)