How to load a relationship in Laravel without foreign key? - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Thursday, June 22, 2023

How to load a relationship in Laravel without foreign key?

I have this model:

App\Controllers\ImageController.php

 .....
    $image = new Image;   
    $image->id = "pre_" . (string) Str::ulid()->toBase58();     
    $image->filename = $filename
    $image->post_id= $post_id;
    $image->save();
    
    return $image->load("post:id,status,subject,body");

it is working fine, it returns the following:

{
  "id": "pre_1BzVrTK8dviqA9FGxSoSnU",
  "type": "document",
  "filename": "v1BzVc3jJPp64e7bQo1drmL.jpeg",
  "post_id": "post_1BzVc3jJPp64e7bQo1drmL",
  "post": {
    "id": "post_1BzVc3jJPp64e7bQo1drmL",
    "status": "active"
    ....
  }
 ....
}

App\Models\Image.php

class Image extends Model
{
    use HasFactory;

    public $incrementing = false; 

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

The issue here is that I don't want it returns the "post_id" field, I would like to get the following:

{
      "id": "pre_1BzVrTK8dviqA9FGxSoSnU",
      "type": "document",
      "filename": "v1BzVc3jJPp64e7bQo1drmL.jpeg",
      "post": {
        "id": "post_1BzVc3jJPp64e7bQo1drmL",
        "status": "active"
        ....
      }
     ....
    }

I tried this:

return $image->select(["id", "type", "filename"])->load("post:id,status,subject,body");

and it returns an error:

"message": "Call to undefined method Illuminate\Database\Eloquent\Builder::load()",

What can I do?



source https://stackoverflow.com/questions/76526241/how-to-load-a-relationship-in-laravel-without-foreign-key

No comments:

Post a Comment