Laravel多个get()请求 - 是否有更好的解决方案?

时间:2017-04-18 07:11:34

标签: php laravel collections eloquent

我目前的项目是一种内部电话簿。用户/管理员无法查看和编辑所有现有联系人,但他可以获得编辑一个或多个部门和/或一个或多个公司(包括所有链接部门)的权限。

  • 用户属于许多公司和/或部门。
  • 联系人属于某个部门。
  • 某个部门属于公司。

我正在使用laravel 5.4并获得以下解决方案。结果是正确的,但它也足够有效和干净?

用户类:

class User extends Authenticatable
{
use Notifiable;


/**
 * The companies that can be edited by the users.
 * 
 * @return void
 */

public function companies()
{
    return $this->belongstoMany(Company::class);
}


/**
 * The departments that can be edited by the user.
 * 
 * @return void
 */

public function departments()
{
    return $this->belongsToMany(Department::class);
}


/**
 * Get all contacts that can be edited by the user.
 * 
 * @return void
 */

public function allContacts()
{
    // Open a new collection
    $contacts = collect();

    // Get all contacts that belongs to all departments
    $this->departments()->get()->each(function ($item) use (&$contacts) {
        $contacts = $contacts->merge(Department::find($item->id)->contacts()->get());
    });

    // Get all contacts that belongs to all companies
    $this->companies()->get()->each(function ($item) use (&$contacts) {
        $contacts = $contacts->merge(Company::find($item->id)->contacts()->get());
    });

    // Return a unique collection
    return $contacts->unique();
}
}

ContactsController:

/**
 * Display a listing of editables contacts.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $contacts = Auth()->user()->allContacts();
    return view('contacts.index', compact('contacts'));
}

allContacts -method中多次使用get()和each()是一种好方法吗?我尽量使用尽可能多的雄辩和收集功能。或者是原始的sql更好的解决方案?

感谢您的支持和好主意:))

1 个答案:

答案 0 :(得分:1)

您的解决方案很糟糕,因为您使用的代码会生成太多查询,而代码本身也无法读取。

使用嵌套的whereHas()代替。一个例子:

$contacts = Contact::whereHas('department.user', function($q) {
    $q->where('id', auth()->id());
})
->orWhereHas('department.company', function($q) {
    $q->whereHas('user', function($q) {
        $q->where('id', auth()->id());
    });
})
->get();