V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
solaro
V2EX  ›  问与答

laravel 的 eloquent 问题寻求帮助

  •  
  •   solaro · 2017-01-10 10:46:12 +08:00 · 1122 次点击
    这是一个创建于 2677 天前的主题,其中的信息可能已经有所发展或是发生改变。

    也许需求: 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 条回复    2017-01-10 17:29:25 +08:00
    ylsc633
        1
    ylsc633  
       2017-01-10 10:54:40 +08:00
    github 随便找个博客,看下他们的 分类 帖子 评论
    或者 权限 角色 用户 关系..
    phpcxy
        2
    phpcxy  
       2017-01-10 11:00:12 +08:00
    ```
    Order::with('goods.barcode')->get();
    ```
    holyghost
        3
    holyghost  
       2017-01-10 11:00:18 +08:00
    https://laravel.com/docs/5.3/eloquent-relationships

    你得送我一个感谢你知道吗
    solaro
        4
    solaro  
    OP
       2017-01-10 17:11:51 +08:00
    @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  
       2017-01-10 17:29:25 +08:00
    @solaro 会有 N+1 的问题吧,不过不重要,你都用 PHP 了你还怕啥。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1195 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:20 · PVG 02:20 · LAX 11:20 · JFK 14:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.