skip to Main Content

I want to fetch only one columns which has name image_url from relationship table. relationship on table is belongsTO.
i am confused how to fetch only single column value with belongsTo relation.

below is my model.


    <?php
    
    namespace AppModels;
    
    use IlluminateDatabaseEloquentFactoriesHasFactory;
    use IlluminateDatabaseEloquentModel;
    
    class PropertyImageGallery extends Model
    {
        use HasFactory;
        protected $fillable = ['property_id', 'name', 'size','image_url'];
    
        public function property()
        {
            return $this->belongsTo(Property::class);
        }
    }

please help me.

3

Answers


  1. BelongsTo relationship like below:

       public function parent()
        {
            return $this->belongsTo(Parent::class,'foreign_key','owner_key');
        }
    

    it would be:

    public function property(){
        return $this->belongsTo(Property::class,'property_id','id');
    }
    
    Login or Signup to reply.
  2. you should call it like this in your controller :

    $yourParentElement = ParentModel::find(1);
    return $yourParentElement ->Property->image_url ;
    

    check this for more infos: Eloquent: Relationships (Belongs To)

    Login or Signup to reply.
  3. You can try this:

    public function property()
    {
        return $this->belongsTo(Property::class)->select(['property_id', '...']);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search