在Laravel中从具有一对一关系的表中获取数据

时间:2018-08-04 15:57:51

标签: php laravel api laravel-5

我正在做我的第一个Laravel项目,我想为Android应用程序创建一个REST Api。在我的系统中,我有两个表:categoriesimages。表images的列category_id是外键,引用了id表上的列category

categories

    //users table migration
    class CreateCategoriessTable extends Migration
    {
        public function up()
        {
         Schema::create('categories', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name');
         $table->timestamps();
        });
       }
...
    }

images

class CreateImagesTable extends Migration
{
    public function up()
    {
        Schema::create('images', function(Blueprint $table){
            $table->increments('id');
            $table->string('name')
            $table->integer('category_id')->unsigned();
            $table->foreign('category_id')
                ->references('id')
                ->on('categories')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }
    ...
}

Images模型类中,我做到了:

class Images extends Model
{
    protected $fillable = ['name'];
    protected $hidden = array('created_at', 'updated_at');

    public function category(){
        $this->belongsTo('App\Category');
    }
}

我还将CategoryResource()类创建为:

class CategoryResource extends JsonResource

    {
          public function toArray($request)
        {
        return [
            'id'=> $this->id,
            'name' => $this->name,
        ];
        }
    }

因此,我使用API​​方法创建了CategoryController,并配置了访问相应功能的路由。通过api/category/的{​​{1}}网址重定向到我控制器的GET函数,该函数是这样的:

index

这样,我可以获得public function index() { $categories = Category::get(); return CategoryResource::collection($categories); } 表数据,但是我想合并categoriesusers表,并得到如下响应:

images

我该怎么做?

1 个答案:

答案 0 :(得分:0)

首先在hasOne模型中为这样的图像添加Category关系

类别模型

public function image(){  
    return $this->hasOne('App\Image');
}

现在在您的CategoryResource

中指定关系
class CategoryResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'=> $this->id,
            'name' => $this->name,
            'image' => new ImageResource($this->whenLoaded('image'))
        ];
    }
}

创建ImageResource来加载图像

class ImageResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'=> $this->id,
            'name' => $this->image_name,
        ];
    }
}

最终将images关系加载到像这样的控制器中急切加载的

public function index()
{
    $categories = Category::with('image')->get();
    return CategoryResource::collection($categories);
}