【问题标题】:Using Laravel with() and all()使用 Laravel with() 和 all()
【发布时间】:2022-01-17 06:37:30
【问题描述】:

目前我有一个名为 ProductLog.php 的模型

class ProductLog extends Model
{
use SoftDeletes, LogsActivity;

protected $table = 'product_logs';

protected static $logAttributes = ['name'];

protected static $logName = 'product_logs';

public function getDescriptionForEvent(string $eventName): string
{
    return "Product Log has been {$eventName}";
}

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'user_id',
    'product_id',
    'json_data',
    'type',
    'name',
    'is_active'
];

public function product()
{
    return $this->belongsTo('App\Services\Products\Product', 'product_id', 'id');
}
public function user()
{
    return $this->belongsTo('App\Services\Users\User', 'user_id', 'id');
}

}

在查询中我使用这个命令来获取我的表 ProductLog 的数据

public function fetchAll() 
{
    return $this->model->with('product','user')->get();
}

我在查询中使用 get();,是否可以从 get(); 切换到 all();

【问题讨论】:

  • Short: No. 这是因为Model::all()Illuminate\Database\Eloquent\Model的静态方法,函数如下:return static::query()->get(...)
  • 真正的问题是为什么?使用 get 而没有额外的查询约束等价于使用 all

标签: php laravel eloquent


【解决方案1】:

简短回答:不。

all() is a method on a Model,它返回一个Collection,它没有with() 方法。

with() is a method on a Model,它返回一个Builder,它没有all() 方法。

因为all()with() 都是Model 方法,所以不能将它们链接在一起。

with()->get() 是正确使用的链,应该会给你想要的结果。

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多