使用 Laravel with() 和 all()
Using Laravel with() and all()
目前我有这个模型叫做 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');
}
}
在查询中,我正在使用此命令获取我的 table ProductLog
的数据
public function fetchAll()
{
return $this->model->with('product','user')->get();
}
我在查询中使用 get();,是否可以从 get(); 切换到 全部();
简答:没有。
all()
is a method on a Model
,其中 returns 一个 Collection
,没有 with()
方法。
with()
is a method on a Model
,其中 returns 一个 Builder
,没有 all()
方法。
因为 all()
和 with()
都是 Model
方法,所以不能将它们链接在一起。
with()->get()
是正确使用的链,应该会给您想要的结果。
目前我有这个模型叫做 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');
}
}
在查询中,我正在使用此命令获取我的 table ProductLog
的数据public function fetchAll()
{
return $this->model->with('product','user')->get();
}
我在查询中使用 get();,是否可以从 get(); 切换到 全部();
简答:没有。
all()
is a method on a Model
,其中 returns 一个 Collection
,没有 with()
方法。
with()
is a method on a Model
,其中 returns 一个 Builder
,没有 all()
方法。
因为 all()
和 with()
都是 Model
方法,所以不能将它们链接在一起。
with()->get()
是正确使用的链,应该会给您想要的结果。