thinkPHP模型关联查询

2025-03-17 23:01:59
推荐回答(2个)
回答1:

price 里用的是belongsTo,只能自动获取一个产品

$price = PriceList::get(1);
//假设产品名称字段是title
echo $price->productlist->title;

product里面是关联了多个价格的

$products =  ProductList::where('status',1)->limit(10)->select();

foreach($products as $product){
    var_export($product->pricelist);
}

这里输出的价格应该是一个列表。

参考: 模型关联 ThinkPHP5.1

回答2:

一对多的查询:

// 这是产品关联价格的一对多查询,可以试试
$productList = ProductList::get(1);
// 也可以进行条件搜索
dump($productList->pricelist()->where('status',1)->select());

一对一的查询:

$priceList = PriceList::get(1);
// 输出User关联模型的属性
echo $priceList->productlist->select();