0

我需要一些有关 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('App\Branch');
    }
}

有数据透视表 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('App\CarMakes', 'car_make_id', 'car_make_id');
    }

    public function model() {
        return $this->hasOne('App\CarModels', 'car_model_id', 'car_model_id');
    }

    public function modification() {
        return $this->hasOne('App\CarModifications', '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('App\Branches', '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 还是有其他更正确的方法来做到这一点?

4

1 回答 1

0

你可以在 laravel 中看到hasManyThrough关系,它会喂饱你。 https://laravel.com/docs/5.8/eloquent-relationships#has-many-through

于 2019-10-28T00:17:08.667 回答