程式碼更新位址
company 物業(yè)表 主表,
propertyMain 小區(qū)表 從表格一個(gè)物業(yè)對應(yīng)多個(gè)小區(qū),一個(gè)小區(qū)對應(yīng)一個(gè)物業(yè)
應(yīng)用場景,小區(qū)增刪改的列表,需要顯示小區(qū)對應(yīng)的 物業(yè)資訊
用 with 取不出來! ! ! !
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PropertyMain extends Model {
protected $table = 'property_main';
public $primaryKey = 'mId';
protected $fillable = [
'mId',
'phone',
'companyId',
];
public function company() {
//參數(shù)1目標(biāo)模型 參數(shù)2當(dāng)前模型與company表關(guān)聯(lián)的外鍵ID 參數(shù)3companny主鍵ID
return $this->belongsTo('App\Models\Company','companyId','mId');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Company extends Model {
protected $table = 'company';
public $primaryKey = 'mId';
protected $fillable = [
'mId',
'name',
'phone',
'introduce'
];
public function propertyMain() {
return $this->hasMany('App\Models\Property','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); // 可以取到數(shù)據(jù)
}
外鍵寫錯了 mId -> companyId
一對多的關(guān)係,PropertyMain 是屬於 Company 的,在 PropertyMain 裡存了 Company 的主鍵作為外鍵,所以外鍵始終是 companyId
public function propertyMain() {
return $this->hasMany('App\Models\PropertyMain','companyId','mId');
}
return $this->hasMany('AppModelsProperty','companyId','mId');
第二個(gè)參數(shù)是目前模型在關(guān)聯(lián)模型裡的外鍵