【问题标题】:Get data from tables with one to one relation for API in Laravel从 Laravel 中 API 的一对一关系的表中获取数据
【发布时间】:2019-01-12 05:06:12
【问题描述】:

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

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,并配置了访问相应功能的路由。通过GETapi/category/ url 重定向到我的控制器的index 函数,函数是这样的:

public function index()
{
    $categories = Category::get();
    return CategoryResource::collection($categories);
}

有了这个,我可以得到categories 表数据,但我想合并usersimages 表,并得到这样的响应:

[
   {
      'id': 1,
      'name': 'category_name',
      'image': 'image_name'
   }
]

我该怎么做?

【问题讨论】:

    标签: php laravel api laravel-5


    【解决方案1】:

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

    类别模型

    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);
    }
    

    【讨论】:

    • @Dexter 我想念你的问题。如果您需要一对一,那么只需在类别模型中添加一个 hasOne 关系并在资源类中进行相应更改。正因为如此,我投了反对票。我会更新我的答案,以便未来的用户不会有问题
    • @Dexter 根据hasOne 关系更新了答案。感谢您的理解并接受我的回答。快乐编码
    猜你喜欢
    • 2019-01-12
    • 2017-10-26
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多