资料00 - Laravel Eloquent:关联

一对多(多对一)

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

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

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PropertyMain extends Model {
    protected $table      = 'property_main';
    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';
    protected $fillable   = [
        'mId',
        'name',
        'phone',
        'introduce'
    ];
    
}

调用

$propertyMains = PropertyMain::with(['company' => function($query) {
    $query->select(['mId', 'name']);},
])->select([
    'id',
    'name',
    'contacts',
    'phone',
    'companyId',
    'created_at',
])->where([])->orderBy('created_at', 'asc')->paginate(12);

你可能感兴趣的:(资料00 - Laravel Eloquent:关联)