首页 > 解决方案 > Laravel,无法获得收藏的财产

问题描述

我有我的表单 obj 的集合,并且我试图让所有页面都属于该表单,当我这样做时,$survey = Forms::find(68)->with('pages')->get();我得到了这个:

Illuminate\Database\Eloquent\Collection {#522 ▼
  #items: array:18 [▼
    0 => App\Models\Forms {#562 ▼
      #table: "forms"
      #fillable: array:4 [▶]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:9 [▶]
      #original: array:9 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "pages" => Illuminate\Database\Eloquent\Collection {#596 ▼
          #items: array:5 [▼
            0 => App\Models\Pages {#628 ▶}
            1 => App\Models\Pages {#632 ▶}
            2 => App\Models\Pages {#633 ▶}
            3 => App\Models\Pages {#634 ▶}
            4 => App\Models\Pages {#635 ▶}
          ]
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
   ]
}

但无法获得关系的属性,当我执行 $form->pages 时,我得到 null 它适用于其他属性,如问题(相同的关系)

这是我的模型:

class Forms extends Model
{
    protected $table = "forms";
    protected $fillable = array('name', 'description', 'status', 'token');


    public function pages()
    {
        return $this->hasMany('App\Models\Pages');
    }
   public function questions()
    {
        return $this->hasMany('App\Models\Question');
    }
}

class Pages extends Model
{
    protected $table = "pages";
    public $timestamps = false;
    protected $fillable = array('name', 'description' ,'priority', 'token');

    public function form()
    {
        return $this->belongsTo('App\Models\Forms');
    }

}

最后,我试图获得结果的方法:

   public function index()
    {

        $survey = Forms::with('pages')->find(68);//Did update regarding to sugestion

        dd($survey);


        return view("pages.surveys", compact('survey'));
    }

谢谢你的帮助。格雷格

标签: phplaraveleloquent

解决方案


我认为你应该颠倒with()andfind()函数的顺序。

$survey = Forms::with('pages')->find(68);

请注意,find()实际执行查询,因此您不必get()再次使用。根据经验:如果您只需要从查询中获取一个结果,您应该使用first()or find()(后者也可用于检索集合),否则使用all()orget()获取结果集合。


推荐阅读