我需要一些关于laravel关系的帮助。我有多个模型,我想通过其他模型得到一个相关模型的结果。
第一种模式:分支
class Branch extends Model
{
protected $table = 'branches';
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = ['name'];
}
第二种模式:用户
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function branches() {
return $this->belongsToMany('AppBranch');
}
}
存在透视表branch_user
第三种型号:汽车
class Cars extends Model
{
protected $table = 'cars';
protected $primaryKey = 'car_id';
protected $fillable = ['car_model_id', 'car_make_id', 'car_modification_id', 'car_registration', 'car_vin', 'owner', 'phone', 'branch_id'];
public function make() {
return $this->hasOne('AppCarMakes', 'car_make_id', 'car_make_id');
}
public function model() {
return $this->hasOne('AppCarModels', 'car_model_id', 'car_model_id');
}
public function modification() {
return $this->hasOne('AppCarModifications', 'car_modification_id', 'car_modification_id');
}
public function getFullName() {
return $this->make->name . " " . $this->model->name . " " . $this->modification->name;
}
public function branch() {
return $this->belongsTo('AppBranches', 'branch_id');
}
}
在这里,我想让所有的汽车可供用户使用。(用户可以指定多个分支(。
class CarsController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function index() {
$cars = Cars::all();
return View::make('cars.list', ['cars' => $cars]);
}
}
希望你们理解我。我应该用HasManyThrough还是有其他更正确的方法?
您可以在laravel中看到hasManyThrough
关系,它会为您提供信息。https://laravel.com/docs/5.8/eloquent-relationships#has-许多通过