solaro
V2EX  ›  问与答

laravel 的 eloquent 问题寻求帮助

  •  
  •   solaro · Jan 10, 2017 · 1556 views
    This topic created in 3408 days ago, the information mentioned may be changed or developed.

    也许需求: 1.需要获取订单和订单的商品详情 2.表 order 、 goods 、 barcode

    现在: order hasMany goods 、 goods hasOne barcode

    怎么写链式?

    Order::with('goods')->get();

    Order 模型里: function goods() { return $this->hasMany(Goods::class, 'id', 'id'); }

    Goods 模型里: function barcode() { return $this->hasOne(Barcode::class, 'id', 'id'); }

    现在懵逼了,不会用。。

    5 replies    2017-01-10 17:29:25 +08:00
    ylsc633
        1
    ylsc633  
       Jan 10, 2017
    github 随便找个博客,看下他们的 分类 帖子 评论
    或者 权限 角色 用户 关系..
    phpcxy
        2
    phpcxy  
       Jan 10, 2017
    ```
    Order::with('goods.barcode')->get();
    ```
    holyghost
        3
    holyghost  
       Jan 10, 2017
    https://laravel.com/docs/5.3/eloquent-relationships

    你得送我一个感谢你知道吗
    solaro
        4
    solaro  
    OP
       Jan 10, 2017
    @holyghost 没有用,用不了。。。 hasManyThrough 吗?

    我最后用蠢办法
    $order_arr = $order->toArray();
    foreach ($order_arr as &$order) {
    foreach ($order['goods'] as &$goods) {
    $barcode = Barcode::where('xxx', xxxx)->first();
    // XXXXBBBBCCCC
    }
    }

    return $order_arr;

    完全没有性能考量呢。。
    holyghost
        5
    holyghost  
       Jan 10, 2017
    @solaro 会有 N+1 的问题吧,不过不重要,你都用 PHP 了你还怕啥。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1284 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 23:43 · PVG 07:43 · LAX 16:43 · JFK 19:43
    ♥ Do have faith in what you're doing.