laravel - Eloquent related model cannot get the data of the related table
我想大声告诉你
我想大声告诉你 2017-05-16 16:47:12
0
3
367

Code update address

company property table main table,
propertyMain community table slave table

One 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); // 可以取到数据 }
我想大声告诉你
我想大声告诉你

reply all (3)
阿神

Hey, the second parameter of belongToMany is the intermediate table, it seems to be missing

    曾经蜡笔没有小新

    The foreign key is written incorrectlymId -> 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

    public function propertyMain() { return $this->hasMany('App\Models\PropertyMain','companyId','mId'); }
      漂亮男人

      return $this->hasMany('AppModelsProperty','companyId','mId');
      The second parameter is the foreign key of the current model in the associated model

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!