控制器給model變量賦值,model里讀取不到值
用的think-orm
控制器代碼
$goods = new GoodsModel();
$goods->_user = 1231;
model里代碼
public $_user = 321;
public function getPriceAttr($value)
{
$value = $value *$this->_user;
return $value;
}
如何將$_user賦值給model里 并讀取到
webman1.4.7
給詳細(xì)代碼吧
控制器里是這樣賦值的
$goods = new GoodsModel();
$goods->_user = 1231;//賦值用戶(hù)數(shù)據(jù)
$detail = $goods->getGoodsDetail($goods_id);
model里
namespace app\api\v1\model;
use think\Model;
class Goods extends Model
{
protected $name = 'skus';//定義表名
public $_user;//定義用戶(hù)數(shù)據(jù)
public function getPriceAttr($value)
{
$value = $this->_user; //取值
return $value;
}
}
$goods = new GoodsModel();
$goods->_user = 1231;//賦值用戶(hù)數(shù)據(jù)
$detail = $goods->getGoodsDetail($goods_id);
$detail->price; // 值是什么
$detail->_user = 1231;
$detail->price; // 值是什么
控制器代碼
public function getGoodsDetail(Request $request)
{
$source = $request->post('source',9);
$goods_id = $request->post('goods_id');
switch ($source) {
case 1:
break;
default:
$goods = new GoodsModel();
$goods->_user = 1231;
$detail = $goods->getGoodsDetail($goods_id);
break;
}
return json(['code'=>0,'data'=>$detail,'msg'=>'獲取成功']);
}
模型代碼
<?php
namespace app\api\v1\model;
use Exception;
use think\Model;
class Goods extends Model
{
protected $name = 'skus';
public $_user;
public function getGoodsDetail($goods_id)
{
try {
$detail =$this->where(['sku'=>$goods_id])->withoutField('state,status_id,created_at,,created_at')->find();
return $detail;
} catch (Exception $e) {
return json(['code'=>-1,'data'=>null,'msg'=>'服務(wù)異常,請(qǐng)聯(lián)系管理員處理!']);
}
}
public function getPriceAttr($value)
{
$value =$value * $this->user;
return $value;
}
}
getGoodsDetail($goods_id) 打印這個(gè)看看是不是模型實(shí)例的(原始)數(shù)據(jù),如果不是 獲取器是不生效的. 用動(dòng)態(tài)獲取器
User::withAttr('name', function($value, $data) {
return strtolower($value);
})->select();
這樣的試試 . 還不行就手動(dòng)吧
你在getGoodsDetail()里返回的是一個(gè)新的model,不是你上面的new GoodsModel(), $_user沒(méi)賦值當(dāng)然是null;
$goods = new GoodsModel();
$goods->_user = 1231; // 這里賦值針對(duì)的是$goods
$detail = $goods->getGoodsDetail($goods_id); // 這里是新的model.即$detail
$detail->_user = 1231; // 這樣才算給model(即$detail)賦值
$detail->price;
你可以嘗試把getGoodsDetail改成,不用ThinkORM,沒(méi)做測(cè)試驗(yàn)證
public function getGoodsDetail($goods_id)
try {
$detail =$this->where(['sku'=>$goods_id])->withoutField('state,status_id,created_at,,created_at')->find();
$detail->_user = $this->_user;
return $detail;
} catch (Exception $e) {
return json(['code'=>-1,'data'=>null,'msg'=>'服務(wù)異常,請(qǐng)聯(lián)系管理員處理!']);
}
}
// 控制器
$goods = new GoodsModel();
$goods->_user = 1231;
$detail = $goods->getGoodsDetail($goods_id);
echo $detail->price;
下次問(wèn)問(wèn)題盡量貼全代碼,不要弄得語(yǔ)焉不詳,溝通起來(lái)累得不行,本來(lái)幾分鐘的事情,浪費(fèi)大家那么多時(shí)間