如何从承包商表中获取或显示公司列并将其放入我的刀片中?我已经尝试通过使用 hasManyThrough 关系来解决这个问题,但它不起作用,因为我引用的所有示例都与我没有相同的流程。
承包商表
id company
住宅表
id contractor_id
买家表
id residential_id
这是模型
承包商.php
<?php
namespace 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
<?php
namespace 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
<?php
namespace 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做这件事:我希望有人帮助我。
当年话下
潇潇雨雨