laravel - laravel-如何通过主表检索名称?
问题描述
我有三个模型,即:
User
Order
UserInfo
在用户模型中:
/* Attribute to set primary user */
protected $primaryKey = 'user_id';
public function userInfo()
{
return $this->hasOne('App\Models\Users\UserInfo', 'user_id');
}
public function orders()
{
return $this->hasMany('App\Models\Orders\Order', 'user_id');
}
在订单模型中:
// Set table
protected $table = 'orders';
// Set timestamps
public $timestamps = true;
// Set primary key
protected $primaryKey = 'order_id';
// Set mass assignable columns
protected $fillable = [];
// Manys orders can belong to one user
public function user()
{
return $this->belongsTo('App\Models\Users\User', 'user_id');
}
在 UserInfo 模型中:
// Set table
protected $table = 'user_infos';
// Set timestamps
public $timestamps = true;
// Set primary key
protected $primaryKey = 'user_id';
// Set mass assignable columns
protected $fillable = [];
/**
* Get the user info associated with the user.
*/
public function user()
{
return $this->belongsTo('App\Models\Users\User', 'user_id');
}
他们的每个表都有一个名为的公共列user_id
,我将通过带有用户 ID 的 Order 模型访问该列,以将其与 User 模型匹配并从 User Info 中检索名称。
我试图用它来检索它,Order::all()->user->userInfo->name->get()
但它说Exception with message 'Property [user] does not exist on this collection instance.'
我做错了什么?
解决方案
您正在尝试将用户关系检索到订单集合中。
它可以从模型实例而不是集合来实现,例如:
$user = Order::first()->user;
如果要显示订单的所有用户,可以遍历订单并检索用户:
foreach($orders as $order){
$user = $order->user;
}
推荐阅读
- android - Kotlin:设置TextView时lateinit属性未初始化
- java - 尝试在java的主类中打印子类方法
- list - 从列表中输出除前 n 个元素之外的元素
- git - 需要帮助使用现有代码设置新的多项目 Git 本地存储库
- post - 使用 POST 方法获取 API 给我 500(内部服务器错误)
- c++ - 实际函数调用计数与 EXPECT_CALL 不匹配
- python - 用于文本搜索的 Python REST Service Now API
- python - 在使用 iloc 的 python 中,您将如何检索数据框中特定列的最后 12 个值?
- r - excelR包R编程中的excelTable没有显示出来
- cmake - 在宏内使用带有 CMake 的 find_package 的 Qt4 出现问题