首页 > 解决方案 > 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.'

我做错了什么?

标签: laravel

解决方案


您正在尝试将用户关系检索到订单集合中。

它可以从模型实例而不是集合来实现,例如:

$user = Order::first()->user;

如果要显示订单的所有用户,可以遍历订单并检索用户:

foreach($orders as $order){
    $user = $order->user;
}

推荐阅读