php - 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'));
}
谢谢你的帮助。格雷格
解决方案
我认为你应该颠倒with()
andfind()
函数的顺序。
$survey = Forms::with('pages')->find(68);
请注意,find()
实际执行查询,因此您不必get()
再次使用。根据经验:如果您只需要从查询中获取一个结果,您应该使用first()
or find()
(后者也可用于检索集合),否则使用all()
orget()
获取结果集合。
推荐阅读
- php - 如何在php中将某些对象属性转换为json
- mysql - magento 2 是否可以在没有 SQL 触发器的情况下工作?
- sql - hsql 给出执行此语句的异常
- c# - 在c#中插入数据库后如何清除文本框值?
- ios - 使用 MPVolumeView 时出现(预期声明)错误
- python - 有没有办法在python中将列表中的所有值单独声明为列表
- php - 在 preg_match() 中存在或放置值
- excel - 将具有更改行数的 Excel 表格链接到 PowerPoint 幻灯片中
- python - 迭代行并加入 python pandas
- continuous-integration - Ci(TravisCI 和 CircleCI)中未安装 Cypress 版本