简体   繁体   中英

How can i select specific field name using belongTo relationship in laravel model using eloquent?

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 App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    
    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.

You can try this:

public function property()
{
    return $this->belongsTo(Property::class)->select(['property_id', '...']);
}

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM