【发布时间】:2020-01-27 22:55:40
【问题描述】:
我有我的表单 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'));
}
感谢您的帮助。 格雷格
【问题讨论】:
-
你在哪里调用 $forms->pages ?
-
我替换 dd($survey);到 dd($survey->pages);并得到 null ,否则得到上面的内容