在这里寻找数据检索专家。我想返回带有图片网址字段的文章。文章模型包含“ file_id”,它是文件模型“ id”的外键。我有一个ArticleResource返回文章。最好的方法是使用id将文件表中的URL插入ArticleResource的url字段中?
ArticleResource:
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'article_content' => $this->article_content,
'article_image' => $this->url,
'article_image_alt' => $this->article_image_alt
];
}
ArticleController:
public function index()
{
//Get Articles
$articles = Article::paginate(10);
$files = File::paginate(10);
// Return collection of articles as a resource
return ArticleResource::collection($articles);
}
商品型号:
class Article extends Model
{
protected $fillable = array('created_at','updated_at','article_title',
'article_content', 'file_id','user_id');
public function file()
{
return $this->hasOne('App\File');
}
public function user()
{
return $this->hasOne('App\User');
}
}
文件模型:
class File extends Model
{
use SoftDeletes;
protected $fillable = [
'title','url','image_alt','created_at','updated_at','deleted_at','user_id'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function article()
{
return $this->belongsTo(Article::class);
}
}