【问题标题】:Getting data related through multiple models通过多个模型获取相关数据
【发布时间】:2019-10-27 20:10:15
【问题描述】:

我需要一些有关 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 还是有其他更正确的方法来做到这一点?

【问题讨论】:

    标签: laravel eloquent laravel-6 laravel-6.2


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2021-05-02
      相关资源
      最近更新 更多