php - 在 laravel 的急切加载中从多对多关系中获取第一个或最新的第一个

标签 php laravel laravel-5.4 eloquent laravel-collection

我正在 laravel 5.4 中构建一个小型应用程序,其中我有两个模型 ContactCompanies 我有很多它们之间有很多关系,在我的 Contact Model:

中是这样的
public function company()
{
    return $this
        ->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')->withTimestamps();
}

现在在某个地方我想要当前公司,即我想要 latest() first()。或者orderBy, created_by desc 得到first()行。为此,我必须做这样的事情:

$contacts = Contact::where('name', 'LIKE', '%'. $request->search_input. '%')
    ->orWhere('email', 'LIKE', '%'. $request->search_input. '%')
    ->orWhereHas('company', function ($q) use($request) {
        $q->where('name', 'LIKE', '%'. $request->search_input. '%');
    })
    ->with('company')
    ->orderBy('created_at', 'desc')
    ->paginate(50);
foreach ($contacts as $contact)
{
    $contact->company = $contact->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first();
}

为了删除 foreach,我尝试在我的 Contact 模型中使用一个新关系:

public function currentCompany()
{
    return $this
        ->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')
        ->withTimestamps()
        ->orderBy('created_at', 'desc')
        ->first();
}

但是在 Controller 中获取时:

$contacts = Contact::where('name', 'LIKE', '%'. $request->search_input. '%')
    ->orWhere('email', 'LIKE', '%'. $request->search_input. '%')
    ->orWhereHas('currentCompany', function ($q) use($request) {
        $q->where('name', 'LIKE', '%'. $request->search_input. '%');
    })
    ->with('CurrentCompany')
    ->orderBy('created_at', 'desc')
    ->paginate(50);

但它给我带来了错误,是否有任何 Eloquent 方式或Collection方式来删除这个foreach

最佳答案

在闭包中使用first()-

$contacts = Contact::where('name', 'LIKE', '%'. $request->search_input. '%')
->orWhere('email', 'LIKE', '%'. $request->search_input. '%')
->with(['company'=>function ($q) use($request) {
    $q->where('name', 'LIKE', '%'. $request->search_input. '%')->first();
}])
->orderBy('created_at', 'desc')
->paginate(50);

或者像这样-

$contacts = Contact::where('name', 'LIKE', '%'. $request->search_input. '%')
->orWhere('email', 'LIKE', '%'. $request->search_input. '%')
->orWhereHas('company', function ($q) use($request) {
    $q->where('name', 'LIKE', '%'. $request->search_input. '%');
})
->with(['company'=>function($q){
       $q->first();  
}])
->orderBy('created_at', 'desc')
->paginate(50);

这样你就不需要做任何额外的foreach循环。

关于php - 在 laravel 的急切加载中从多对多关系中获取第一个或最新的第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48376610/

相关文章:

PHP PDO 数据库备份类

php - 使用 HTML 输入的标记属性进行 SQL 查询,而不泄露数据库表行 ID

java - 论坛设计的混合内容警告

php - 防止无状态系统中重复的表单提交

javascript - Vue.js 和 Laravel 返回 json 和资源的区别

php - 使用 SSL 时无法连接到 MySQL

php - laravel 5 根据路由返回 HTML 或 JSON

javascript - 使用 laravel mix 包含 js 依赖

php - Laravel 如何在提交时将我的身份验证用户 ID 插入到我的数据库中?

laravel - 从 laravel 中删除一个包