亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Laravel 中使用有很多 through 關系

在 Laravel 中使用有很多 through 關系

PHP
慕田峪7331174 2024-01-19 15:02:14
如何從承包商表中獲取或顯示公司列并將其放入我的刀片中?我已經嘗試通過使用 hasManyThrough 關系來解決這個問題,但它不起作用,因為我引用的所有示例都與我沒有相同的流程。承包商表id  company住宅表id contractor_id買家表id residential_id這是模型承包商.php<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Contractor extends Model{    protected $table = 'contractors';    protected $fillable = ['user_id','company','address','phone_no','email','avatar'];    public function residential()    {        return $this->hasMany(Residential::class);    }    public function buyers()    {        return $this->hasManyThrough('App\Buyer', 'App\Residential');    }    public function buyer()    {        return $this->hasOneThrough('App\Buyer', 'App\Residential');    }}如果我執行這種代碼,它將是$contractor->buyer。雖然我希望它是 $buyer->contractor->company買家.php<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Buyer extends Model{    protected $fillable = ['buyer_id', 'name', 'address', 'phone_no', 'email', 'avatar', 'user_id', 'residential_id'];    public function residential()    {        return $this->belongsTo(Residential::class);    }}住宅.php<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Residential extends Model{    protected $fillable = ['name','res_code','postcode','city','state','image','contractor_id'];    public function contractor()    {        return $this->belongsTo(Contractor::class);    }    public function buyer()    {        return $this->hasMany(Buyer::class);    }}BuyerController.php public function index(Request $request)    {        if(Auth::user()->role == 'buyer')            {                $buyers = Buyer::where('user_id', '=', Auth::id())->first();                return view('buyers.index',['buyer'=>$buyers]);            }這是我正在處理的視圖,并且沒有循環,因為這是買家登錄的個人資料。根據上面的查看代碼,我已經為Residence做好了關系:但我無法為Contractor做這件事:我希望有人幫助我。
查看完整描述

2 回答

?
當年話下

TA貢獻1890條經驗 獲得超9個贊

嘗試這個

那么你可以做

$buyer->contractor->company

$buyer->residential->contractor->company

你已經添加belongsTo了 2 個模型


查看完整回答
反對 回復 2024-01-19
?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

在控制器中

$buyers = Buyer::where('user_id', '=', Auth::id())->first();
    return view('buyers.index',['buyer'=>$buyers]);

然后調用blade文件

$buyers->residential->contractor->company


查看完整回答
反對 回復 2024-01-19
  • 2 回答
  • 0 關注
  • 178 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號