Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

新手学习tp5
有两个表
teacher:id name username
klass:id name teahcer_id

现在需要在模板页面循环输出klassd的内容,其中,希望把klass里面的teacher_id转换成teacher里面的name来显示。

正常情况下:
$klass->teahcer_id 返回的是id
如果想得到是teacher.name 必须再去查teacher

用klass的字段作为查询条件,放到teacher里面去查询name.
想到的是封装成一个函数:

public function getTeacher($teacher_id){
$teacher = TeacherModel::get($teacher_id);
return  $teacher->name; 
}

这个方法放哪里呢,因为在模板里面是循环输出klass的内容,

 {volist?id="Klass"?name="Klasses"}
 <tr>
 <td>{$i}</td>
 <td>{$Klass.id}</td>
 <td>{$Klass.name}</td>
 <td>{$Klass->getTeacher({$Klass.teacher_id})}</td>
 <td>
 <a
 type="button"
 class="btn?btn-warning"
 href="{:url('delete?id='.$Klass->getData('id'))}"
 >删除</a>
 <a
 type="button"
 class="btn?btn-info"
 href="{:url('edit?id='.$Klass->getData('id'))}"
 >编辑</a
 >
 </td>
 </tr>
 {/volist}
 </tbody>
 </table>
 {$Klasses->render()}

所以方法应该放在klass模型里面:

use appindexmodelTeacher as TeacherModel;
class Klass extends Model
{
 public function getTeacher($teacher_id)
 {
 $Klass = TeacherModel::get($teacher_id);
 return $Klass['name'];
 }
}

然后在模板内这样调用了:

{$Klass->getTeacher({$Klass.teacher_id})}

发现最后渲染的结果:
{$Klass->getTeacher(1)}
{$Klass->getTeacher(2)}
之类的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
957 views
Welcome To Ask or Share your Answers For Others

1 Answer

啊,我自己是。。。。
模板调用应该是这样的:

{$Klass->getTeacher($Klass.teacher_id)}

最里面的{}不需要了.....


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...