Eloquent withtrashed() 用于在急切加载查询上进行软删除 - Laravel 5.1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33900124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent withtrashed() for soft deletes on eager loading query - Laravel 5.1
提问by user3489502
I'm trying to use withTrashed() with eager loading. I've created a new _withtrashed function in my model, but the query comes back with a NULL for my client
我正在尝试使用 withTrashed() 进行急切加载。我在我的模型中创建了一个新的 _withtrashed 函数,但是我的客户的查询返回一个 NULL
Client model:
客户端模型:
// Client
public function client()
{
return $this->belongsTo('App\Client');
}
// Client (withtrashed for soft deletes)
public function client_withtrashed()
{
return $this->belongsTo('App\Client')->withTrashed();
}
Order controller:
订单控制器:
/**
* Show order.
*/
public function show($id)
{
$order = Order::with('client_withtrashed') ---> it works normally with: Order::with('client') , except I don't get the soft deleted rows
->where('id', '=', $id)
->firstOrFail();
dd($order); displays an empty client
dd($订单);显示一个空的客户端
#relations: array:1 [
"client_withtrashed" => null
Any ideas? I decided on the solution above because I couldn't get withTrashed() to work with my eager query $order = Order::with('client_withtrashed')->withTrashed()
有任何想法吗?我决定采用上面的解决方案,因为我无法使用 withTrashed() 来处理我急切的查询 $order = Order::with('client_withtrashed')->withTrashed()
回答by Fabio Antunes
Well you can't define that on a relationship, but you can add constraints when you are eager loading:
好吧,您不能在 relationship 上定义它,但是您可以在急切加载时添加约束:
$order = Order::with(['client' => function ($query) {
$query->withTrashed();
}])
->where('id', '=', $id)
->firstOrFail();
You can check the eager loading constraints in the docs
您可以在文档中检查预先加载约束
EDIT:
编辑:
You can define withTrashed()on your relationship, just make sure that your models are using the SoftDeleteTrait.
您可以在关系上定义 withTrashed(),只需确保您的模型使用 SoftDeleteTrait。
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Client extends Eloquent {
use SoftDeletingTrait;
}
回答by sh6210
In my case
就我而言
\App\User::withTrashed()->findOrFail($userId)->first()
is giving me the wrong data (was giving the auth user data) then,
给了我错误的数据(给了授权用户数据)然后,
\App\User::withTrashed()->whereId($userId)->first()
gave me the exact data.
给了我确切的数据。