【问题标题】:withTrashed on hasManyThrough relationwithTrashed on hasManyThrough 关系
【发布时间】:2017-11-12 14:19:13
【问题描述】:

如何将withTrashed 应用于hasManyThrough 关系?

$this->hasManyThrough('App\Message', 'App\Deal')->withTrashed();

返回

调用未定义的方法 Illuminate\Database\Query\Builder::withTrashed()

当我在做的时候:

$messages = Auth::user()->messages()->with('deal')->orderBy('created_at', 'DESC')->get();`

这是我的交易模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Deal extends Model
{

    use SoftDeletes;

    /* ... */

    protected $dates = ['deleted_at'];

    public function user() {
        return $this->belongsTo('App\User');
    }

    public function messages() {
        return $this->hasMany('App\Message'); // I've tried to put withTrashed() here, there is no error but it doesn't include soft deleting items.
    }
}

【问题讨论】:

  • 你是否也在Message模型中使用SoftDeletes trait?
  • 不,邮件永远不会被删除
  • -&gt;hasManyThrough('App\Message', 'App\Deal')-&gt;withTrashed()这一行中,您请求带有已删除消息的消息,并且您没有使用SoftDelete trait,这就是引发异常的原因,您必须删除withTrashed函数
  • 我怎样才能要求属于已删除交易的消息?
  • 我发现这种方式没有办法,我添加一个答案也许对你有帮助

标签: laravel laravel-5 eloquent


【解决方案1】:

对于所有迟到的人,现在有一种使用 Laravel 的原生方式。

$this->hasManyThrough('App\Message', 'App\Deal')->withTrashedParents();

这没有很好的记录,但可以在Illuminate\Database\Eloquent\Relations\HasManyThrough中找到

【讨论】:

  • 这是在 Laravel 7.x 中实现的。它不适用于 Laravel 5 或 6
【解决方案2】:

抛出错误是因为您在 Message 模型中未使用 SoftDelete 特征而请求删除的消息。

我查了hasManyThrough关系代码后发现,这种方式是不行的,你自己玩玩吧。

例如:

改为通过消息获取用户的交易

$deals = Auth::user()->deals()->withTrashed()->with('messages')->get();
foreach($deals as $deal) {
     //Do your logic here and you can access messages of deal with $deal->messages
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2018-07-24
    • 2018-10-18
    • 2023-03-09
    • 2021-06-09
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多