使用模型功能

时间:2019-09-24 14:46:27

标签: laravel

我有如下的Category模型

class Category extends Model
{    
    public function users(){
        return $this->hasMany(User::class)->where("active_status",1)->where("user_type", 'user');
    }
}

我有如下的User模型

class User extends Authenticatable
{
    public function getFullName()
    {
        return $this->first_name.' '.$this->middle_name.' '.$this->last_name;
    }
}

我的控制器代码如下

$category = Category::join('users', 'users.category_id', '=', 'categories.id')->get(); 

我正在尝试使用view

中的以下代码
@foreach( $result as $spc )

  $spc->getFullName();

@endforeach

我遇到如下错误

[2019-09-24 14:45:43] laravel.ERROR: Call to undefined method App\Category::getFullName()

1 个答案:

答案 0 :(得分:3)

在评论之后,实现目标的最佳方法是正确使用Eloquent relationships

因此,在您的控制器中,将您的查询从以下位置更改

$category = Category::join('users', 'users.category_id', '=', 'categories.id')->get();

$categories = Category::with('users')->get();

现在,结果将是Category的集合,该集合急切地加载了users关系,例如:

[
  {"id": 1, "name": "My category 1", "users": [{"id": 1, "mail": "user1@example.com"}, {"id": 2, "mail": "user2@example.com"}]},
  {"id": 2, "name": "My category 2", "users": []},
  {"id": 3, "name": "My category 3", "users": [{"id": 7, "mail": "user7@example.com"}]},
]

使用简单的foreach在您的视图中,您可以迭代类别和每个用户:

<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Users</th>
        </tr>
    </thead>
    <tbody>
        @foreach($categories as $category)
        <tr>
            <td>
                {{ $category->id }}
            </td>
            <td>
                {{ $category->name }}
            </td>
            <td>
                <ul>
                    @foreach($category->users as $user)
                    <li>
                        {{ $user->getFullName()}}
                    </li>
                    @endforeach
                </ul>
            </td>
        </tr>
        @endforeach
    </tbody>
</table>

旁注

我看到您的关系被声明为

public function users(){
    return $this->hasMany(User::class)->where("active_status",1)->where("user_type", 'user');
}

我不太希望在关系声明中添加所有这些where。我认为使用local scopes是更好的方法,因为该代码可能会在您代码的其他部分使用。