Laravel访问其他人对象的值

时间:2017-08-08 14:40:19

标签: laravel laravel-5

我有3张桌子: -

available_offers - id
- 日期
- 时间
- 来自 - 到 - user_id

requested_offer - id
- user_id
- available_offersID

用户 - id
- 姓名
- 用户名
- 密码
- 电子邮件

这里是我的routes_bookedController

class routes_bookedController extends Controller
{
public function create() 
{
    $user = available_offers::with('user')->get();
    $booked = requested_routes::with('available_offers', 'user')
            ->where('user_id', Auth::id())
            ->get();

    return $booked;

    return view ('routes_booked.show', compact('booked'));
   }
}

这是来自routes_bookedController

的show.blade.php的结果
[
   {
      "id": 3,
      "user_id": 4,
      "available_offersID": 3,
      "created_at": null,
      "updated_at": null,
      "available_offers": {
           "id": 3,
           "date": "2017-08-08",
           "time": "14:11:30",
           "from": "Sabah",
           "to": "Sarawak",
           "user_id": 2,
           "isBooked": 1,
           "created_at": null,
           "updated_at": null
   },
      "user": {
           "id": 4,
           "name": "admin",
           "username": "user1",
           "email": "user1@example.com",
           "created_at": "2017-08-08 06:15:49",
           "updated_at": "2017-08-08 06:15:49"
      }
   }
 ]

是否可以从available_offers-> user->名称获取名称?

这是我的模特: -

  1. requested_routes

    class requested_routes extends Model
    {
    public function available_offers()
    {
        return $this->belongsTo(available_offers::class, 'available_offersID');
    }
    
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    }
    
  2. available_offers

    class available_offers extends Model
    {
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    
    public function requested_routes() 
    {
        return $this->hasMany(requested_routes::class);
     }
     }
    
  3. 用户

    public function available_offers() 
    {
       return $this->hasMany(available_offers::class);
    }
    
    public function requested_routes()
    {
       return $this->hasMany(requested_routes::class);
    }
    

1 个答案:

答案 0 :(得分:0)

急切加载子模型

$booked = requested_routes::with('available_offers', 'available_offers.user', 'user')
         ->where('user_id', Auth::id())
         ->get();

确保将 available_offers.user 添加为with子句之一。