如何在yii中的findbyPk()方法中获取单个值?

jgzswidk  于 2022-11-09  发布在  其他
关注(0)|答案(6)|浏览(149)

在我的控制器中

$agent = University::model()->findByPK($university_id);

我希望它会返回一行值的值。我想要一个单一的属性(field3)值比如university_name,(不使用findByPK),如何得到它

SELECT  field3 FROM table [WHERE Clause]
jv4diomz

jv4diomz1#

试试这个

$usercriteria = new CDbCriteria();
$usercriteria->select = "university_name";
$usercriteria->condition = "university_id=$university_id";
$university = University::model()->findAll($usercriteria);

echo $university->university_name;

或者就像你第一次那样

$agent = University::model()->findByPK($university_id);
echo $agent-> university_name;
r1zk6ea1

r1zk6ea12#

$agent = University::model()->findByPK($university_id);
echo $agent->university_name;
pbpqsu0x

pbpqsu0x3#

它应该是这样的:

$agent = University::model()->findByPK($university_id)->university_name;
mum43rcc

mum43rcc4#

试试看:

$university_name = University::model()->findByPK($university_id, array('select'=>'univeersity_name'))->university_name;

# Query: SElECT university_name FROM table_name where id=x;

而不是

$university_name = University::model()->findByPK($university_id)->university_name;

# Query: SElECT * FROM table_name where id=x;

第二个查询返回所有字段。所以最好避免那些字段是不必要的。

3phpmpom

3phpmpom5#

如果你需要在yii _views上查看,我已经在我的项目上实现了这个,我把它放在我的'_view.php'里面,地址是/protected/views/myTable/

$agent = University::model()->findByPK($data->id_university/*this is the PK field name*/);
echo $agent->university_name /*university field name*/;

再次为我糟糕的英语道歉:o

dgiusagp

dgiusagp6#

可以这样做:

$agent = University::model()->findAllByAttributes(array('field3'),"WHERE `id` = :id", array(':id' => $university_id));

findByAttributes的第一个参数是您希望它返回的属性数组。如果保留为空,它将返回all(*)。

相关问题