我在尝试使用Eloquent模型执行真正基本的查询时遇到了麻烦,其中 create 和 find 都可以正常工作但其中没有回报。
型号:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'companies';
protected $fillable = ['name', 'ticker', 'industry', 'sector', 'description'];
protected $visible = ['name', 'ticker', 'industry', 'sector', 'description'];
}
控制器:
创建正常工作:
\App\Company::create(['ticker'=>'AAPL', 'name' => 'Apple Inc']);
在DB上创建一个新行:
(id,name,ticker)
1,Apple Inc,AAPL
查找正常工作:
$company = \App\Company::find(1);
print_r($company);
返回
App \ Company Object([table:protected] => companies [fillable:protected] => Array([0] => name [1] => ticker [2] => industry [3 ] => sector [4] => description)[visible:protected] =>数组([0] => name [1] => ticker [2] => industry [3] => sector [4] => description)[connection:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [递增] => 1 [timestamps] => 1 [ attributes:protected] =>数组([id] => 1 [名称] => Apple Inc [ticker] => AAPL [industry] => [sector] => [description] => [ created_at] => 2016-01-14 00:01:35 [updated_at] => 2016-01-14 00:01:35)[original:protected] =>数组([id] => 1 [ name] => Apple Inc [ticker] => AAPL [industry] => [sector] => [description] => [created_at] => 2016-01-14 00:01:35 [updated_at ] => 2016-01-14 00:01:35)[relations:protected] => Array()[hidden:protected] => Array()[appends:protected] =>数组( )[guarded:protected] =>数组([0] => *)[日期:受保护] => Array()[dateFormat:protected] => [casts:protected] => Array()[touches:protected] => Array()[observables:protected] => Array()[with:protected] => Array()[morphClass:protected] => [exists] => 1 [wasRecentlyCreated] => )
现在,当我尝试使用除id之外的任何字段进行搜索时,它根本不返回任何内容:
$company = \DB::table('companies')->select('ticker', 'name')->where('ticker', '=', 'AAPL')->get();
print_r($company);
返回一个空数组:
Array()
两者都是:
$company = \App\Company::find(['ticker', 'AAPL'])->first();
print_r($company);
和
$company = \App\Company::where('ticker', '=', 'AAPL')->first();
print_r($company);
他们根本就什么也没回来。
--- ---更新
迁移:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCompaniesTable extends Migration
{
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('ticker');
$table->string('industry')->nullable();
$table->string('sector')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::drop('companies');
}
}
答案 0 :(得分:0)
<强>固定强>
我从其他网站上阅读的代码附带了奇怪的特征(感谢@ceejayoz,谢谢你的帮助)
创建一个Company
手动工作正常,因为我正在'硬编码'自动收报机:
\App\Company::create(['ticker'=>'AAPL', 'name' => 'Apple Inc']);
至于我从其他网站上删除的公司,在存储之前这样做是有诀窍的:
str_replace(array('.', ' ', "\n", "\t", "\r"), '', $ticker);
显然,如果自动收报机有一个进位和/或零长度空间,并且我使用修剪的自动收报机查询结果为空。更新后的代码Model
适用于:
$company = \App\Company::where('ticker', '=', $ticker)->first();