Code update address
company property table main table,
propertyMain community table slave tableOne property corresponds to multiple communities, and one community corresponds to one property
Application scenario, the list of community additions, deletions and modifications needs to display the corresponding property information of the community
Can’t get it out using 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() { //参数1目标模型 参数2当前模型与company表关联的外键ID 参数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); // 可以取到数据 }
Hey, the second parameter of belongToMany is the intermediate table, it seems to be missing
The foreign key is written incorrectly
mId -> companyId
In a one-to-many relationship, PropertyMain belongs to Company. The primary key of Company is stored in PropertyMain as a foreign key, so the foreign key is always companyId
return $this->hasMany('AppModelsProperty','companyId','mId');
The second parameter is the foreign key of the current model in the associated model