我正在开发一个系统,该系统使用Maatwebsite从excel工作表中读取数据并将数据写入数据库,效果很好。现在,在插入数据之前,系统将检查父表中的条目。并且如果有任何与工作表记录匹配的记录,则系统将外键插入子模式,如果没有,则系统首先创建一个子键,然后将其ID作为外键插入。
这是导入类:
public function collection(Collection $rows){
$sub_chap = SubChapter::where(['chap_id' => $this->chap_id])->get();
$chapter = Chapter::where(['chap_id' => $this->chap_id])->first();
$author = Author::where(['author_status' => 1])->get();
$book = $chapter->book_id;
$author_id = 0;
$sub_chap_id = 0;
/* Working perfectly fine here...
foreach($author as $a){
echo $a->a_name."\r";
}
*/
foreach ($rows as $row){
if($row['quote_english'] != ""){
foreach($sub_chap as $sub){
if(trim($sub->sub_chap_english) == trim($row['sub_chap_english'])){
$sub_chap_id = $sub->sub_chap_id;
break;
} else{
$sub_chap_id = 0;
}
}
if($author->count() > 0){
foreach($author as $athr){
$author_id = (trim($athr->author_name) == trim($row['author_name']))? $athr->author_id : $author_id = 0;
}
}
if($author_id == 0){
$author = Author::create([
'author_name' => $row['author_name'],
...
...
'author_status' => 1,
]);
$author_id = $author->author_id;
}
$quote = Quote::create([
'quote_english' => $row['quote_english'],
'author_id' => $author_id,
'sub_chap_id' => $sub_chap_id,
'chap_id' => $this->chap_id,
'book_id' => $book
]);
}
}
}
这句话是:
试图获取非对象的属性“ author_name”
我知道当您尝试从非对象实例访问对象的属性时出现此错误。 get()照常返回集合对象,并在foreach()循环外正常工作。我无法弄清楚的是为什么它在循环中不起作用。任何帮助将不胜感激!
答案 0 :(得分:0)
我仍然不知道为什么这么说,而且似乎也没有。所以我认为是时候发布我想出的解决方案了。我找到了解决方法,所以基本上,我所做的就是将整个集合存储到全局变量中,并在循环中访问它。
以下是代码:
/**
* Global variable for raavi's data.
*/
public $author;
/**
* Construction function.
*
* @param int $id
* @param Collection $arr
*/
function __construct($arr) {
$this->author= $arr;
}
/**
* This method is responsible for inserting the excel
* sheet's rows data to the database schema.
*
* @param Collection $rows
*/
public function collection(Collection $rows){
// other code as it is...
foreach($this->author['author'] as $athr){
$author_id = (trim($athr->a_name) == trim($row['author_name']))? $athr->a_id : 0 ;
}
}
以及我的导入控制器的导入方法:
$quotes = Excel::import(new QuotesImport(compact('author')));
到目前为止工作正常。如果有任何改进或需要更改的地方,请放心。我会很感激的。