php - laravel 查找数据 Eloquent ORM 查询
ringa_lee
ringa_lee 2017-04-10 15:45:48
[PHP讨论组]

现在 有 2个 表
goods 和 products

 $products = Goods::where('merchant_id','=','5')->get();


 foreach($products as $p){
            print_r($p->product_id);
            $_name = Product::where('id','=',$p->product_id)->get();
            $_name = $_name[0];

}

首先 我们去 goods 表 去 查询 merchant_id = 5 的 商品;

因为 在 goods 表里面 没有 改 商品的 名字 和 更多详细的信息 ;

所以 需要 循环 goods 表里查询到的数据 通过 goods 表的 product_id 字段 去 products 查询 products 的 id 字段 所匹配的 更多信息 (name ) 等等

改怎么查询呢

我现在想到的 是 给 $products 这对象 循环添加查询到的 名字

有大神指导一下吗 (*^__^*) 嘻嘻……

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
怪我咯
phpclass Goods extends Model {

    public function product()
    {
        return $this->belongsTo('App\Products');
    }
}
$products = Goods::with('product')->where('merchant_id','=','5')->get();//数组里的product就是goods 表的 product_id 对应products的信息
高洛峰
我一般这么做 牵扯到两张表的查询 我会使用 fluent query buid 即:

$result = DB::table('goods')
            ->select(DB::raw('goods.*, products.*'))
            ->where('goods. merchant_id', '=', 5)
            ->join('products', 'goods.product_id', '=', 'products.id')
            ->get();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号