[英]Error with Eloquent ORM in laravel 4
我目前正在學習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();
}
據我所知,您的示例不起作用,因為您沒有創建新的Photo模型。
嘗試替換此:
$logged_in_user->photos()->save($photos);
與:
foreach ($photos as $photoData) {
$photo = new Photo($photoData);
$logged_in_user->photos()->save($photo);
}
您不需要使用$logged_in_user
進行關聯,因為您已經在數組中設置了ID,因此只需使用create
。
Photo::create($photos);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.