Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

Eloquent 关联模型 取不出关联表的数据

代码更新地址

company 物业表 主表,
propertyMain 小区表 从表

一个物业对应多个小区,一个小区对应一个物业

应用场景,小区增删改的列表,需要显示小区对应的 物业信息

用 with 取不出来!!!!

namespace AppModels;
use IlluminateDatabaseEloquentModel;
class PropertyMain extends Model {
    protected $table      = 'property_main';
    public    $primaryKey = 'mId';
    protected $fillable   = [
        'mId',
        'phone',
        'companyId',
    ];

    public function company() {
        //参数1目标模型 参数2当前模型与company表关联的外键ID 参数3companny主键ID
        return $this->belongsTo('AppModelsCompany','companyId','mId');
    }
}
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Company extends Model {
    protected $table      = 'company';
    public    $primaryKey = 'mId';
    protected $fillable   = [
        'mId',
        'name',
        'phone',
        'introduce'
    ];
    
    public function propertyMain() {
        return $this->hasMany('AppModelsProperty','mId','mId');
    }
}
$propertyMains = PropertyMain::with('company')->get();
foreach ($propertyMains as $b){
    dd($b->company); // 返回空
}
$propertyMains = PropertyMain::where([])->orderBy('created_at', 'asc')->paginate(12);
foreach ($propertyMains as $b){
    dd($b->company); // 可以取到数据
}

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

1 Reply

0 votes
by (71.8m points)

哎,belongToMany第二个参数是中间表吧,好像漏了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...