簡體   English   中英

我如何在 laravel model 使用 eloquent 中使用屬於關系的 select 特定字段名稱?

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

我只想從關系表中獲取名稱為image_url的一列。 表上的關系是 belongsTO。 我很困惑如何只獲取具有 belongsTo 關系的單個列值。

下面是我的 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);
        }
    }

請幫我。

你可以試試這個:

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

BelongsTo 關系如下:

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

這將是:

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

你應該在你的 controller 中這樣稱呼它:

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

檢查此以獲取更多信息: Eloquent:關系(屬於)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM