Laravel 4 中 Eloquent ORM 错误
题
我目前正在学习 Laravel 并尝试遵循本教程。但我使用 laravel 4 并且教程使用 laravel 3,所以我应该因此修复很多东西。我在控制器上有这个方法
public function InsertTestData()
{
$logged_in_user = Auth::user();
$photos = array(
array(
'user_id' => $logged_in_user->id,
'location' => 'http://farm6.staticflickr.com/5044/5319042359_68fb1f91b4.jpg',
'description' => 'Dusty Memories, The Girl in the Black Beret (http://www.flickr.com/photos/cloudy-day/)'
),
array(
'user_id' => $logged_in_user->id,
'location' => 'http://farm3.staticflickr.com/2354/2180198946_a7889e3d5c.jpg',
'description' => 'Rascals, Tannenberg (http://www.flickr.com/photos/tannenberg/)'
),
array(
'user_id' => $logged_in_user->id,
'location' => 'http://farm7.staticflickr.com/6139/5922361568_85628771cd.jpg',
'description' => 'Sunset, Funset, Nikko Bautista (http://www.flickr.com/photos/nikkobautista/)'
)
);
$logged_in_user->photos()->save($photos);
}
这是我使用的模型
class User extends Eloquent implements UserInterface, RemindableInterface {
public function photos()
{
return $this->hasMany('Photo');
}
}
它会像这样返回错误
Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in /Library/WebServer/Documents/webpraktek/app/controllers/DashboardController.php on line 44 and defined
第 44 行是这一行
$logged_in_user->photos()->save($photos);
这是班级照片的模型
class Photo extends Eloquent
{
public function user()
{
return $this->belongsTo('User');
}
public function photocomments()
{
return $this->hasMany('PhotoComment');
}
}
我不知道有什么可以解决这个问题,因为我还在学习。为什么会发生这种情况?laravel 版本的不同是否会导致这种错误?谢谢
编辑:我暂时用这个修复了它,
foreach($photos as $photo) {
$photos = new Photo();
$photos->user_id = $photo['user_id'];
$photos->location = $photo['location'];
$photos->description = $photo['description'];
$photos->save();
}
解决方案
据我所知,你的例子不起作用,因为你不是创建一个新的照片型号。
尝试更换:
$logged_in_user->photos()->save($photos);
.
:
foreach ($photos as $photoData) {
$photo = new Photo($photoData);
$logged_in_user->photos()->save($photo);
}
. 其他提示
你不需要使用 $logged_in_user
关联,因为你已经在数组中设置了 ids,所以只需使用 create
反而。
Photo::create($photos);
不隶属于 StackOverflow