TP5
hasMany('关联模型名','外键名','主键名',['模型别名定义']);
model 模组
<?php
namespace appindexmodel;
use thinkModel;
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/1/2
* Time: 22:06
*/
class Banner extends Model
{
public function comments()
{
return $this->hasMany('Comment','memberid','px')->field('id,goodsid,memberid,content,add_time');
}
}
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/1/2
* Time: 22:11
*/
namespace appindexmodel;
use thinkModel;
class Comment extends Model
{
}
控制器
<?php
namespace appindexcontroller;
use appindexmodelBanner;
class Index
{
public function index()
{
$article =new Banner();
$arr = Banner::with('comments')->paginate(1);
echo "<pre>";
foreach($arr as $key => $value){
print_r($value->toArray());
}
// return View('index');
}
}
修改数据字段
原有模型中 利用获取器替换
<?php
namespace appindexmodel;
use thinkModel;
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/1/2
* Time: 22:06
*/
class Banner extends Model
{
public function comments()
{
return $this->hasMany('Comment','memberid','px')->field('id,goodsid,memberid,content,add_time');
}
public function getUrlAttr() //获取器使用修改URL参数
{
return $this->hasMany('Comment','memberid','px')->value('content');//修改URL 参数
}
}
有更好的方法 可以评论 告诉我 PHP小白一名最近在 用TP5写项目!谢谢!
模型获取器 自定义字段
<?php
namespace appindexmodel;
use thinkModel;
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/1/2
* Time: 22:06
*/
class Banner extends Model
{
protected $append = [
'typeText'
];
public function comments()
{
return $this->hasMany('Comment','memberid','px')->field('id,goodsid,memberid,content,add_time');
}
public function getUrlAttr()
{
return $this->hasMany('Comment','memberid','px')->value('content');
}
public function getTypeTextAttr($value, $data)
{
return $this->typeText[$data['url_type']] ?? '12121';
}
}