laravel 试图读取int的属性

yc0p9oo0  于 2023-01-10  发布在  其他
关注(0)|答案(3)|浏览(126)

我的关系:
内容模式=〉

class Content extends Model
{
    use HasFactory;

    protected $table = "contents";

    protected $fillable = [ "body", "camapaign_id" ];

    public function campaigns(){
        return $this->belongsTo(Campaign::class, "campaign_id");
    }
}

我的手机模型=〉

class Campaign extends Model
{
    use HasFactory;

    protected $table = "campaigns";

    protected $fillable = [ "ringba_campaign_id", "is_active" ];

    public function contents(){
        return $this->hasMany(Content::class, "content_id");
    }
}

以下是我的迁移:
内容表=〉

public function up()
    {
        Schema::create('contents', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string("body", 255);
            $table->foreignIdFor(\App\Models\Campaign::class)->nullable();
        });
    }

活动表=〉

public function up()
    {
        Schema::create('campaigns', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string("ringba_campaign_id", 255);
            $table->boolean("is_active")->default(0);
        });
    }

下面是我的内容控制器:

public function index(){
        $contents = Content::all()->sortBy("created_at");
        return view("Dashboard.Contents.contents", [
            "contents" => $contents
        ]);
    }

我正在尝试访问ringba_camapaign_id,如下所示=〉

@foreach($contents as $content) 
  {{ $content->campaign_id->ringba_campaign_id }}
 @endforeach

但我得到这个错误:试图读取int的属性

8ftvxx2r

8ftvxx2r1#

这里有两件事,因为Content BelongsTo a Campaign方法应该是单数的。

public function campaign(): BelongsTo
{
    return $this->belongsTo(Campaign::class, 'campaign_id');
}

然后,当您执行$content->campaign_id时,您将获得模型的属性,因此将返回一个int。您要做的是通过内容模型中定义的关系返回活动模型,如$content->campaign。现在,您可以访问活动模型$content->campaign->ringba_campaign_id的属性。
然而,它看起来也像是一个活动可以为空的迁移,所以你需要添加保护,这样你就不会得到空错误的属性。所以这将看起来像optional($content->campaign)->ringba_campaign_id,如果内容没有活动,这将返回空。

klh5stk1

klh5stk12#

实际上我在内容模型里面写了不好的关系代码:
之前我写道:

public function campaigns(){
return $this->belongsTo(Campaign::class);
}

答案将是:

public function campaign(){
    return $this->belongsTo(Campaign::class);
    }

我写的是竞选而不是竞选。

j8yoct9x

j8yoct9x3#

试试这个。

@foreach($contents as $content) 
  {{ $content->campaigns->ringba_campaign_id }}
@endforeach

有关详细信息,请检查此链接

相关问题