Answer the question
In order to leave comments, you need to log in
Is the One-to-Many relationship correct?
Laravelers, save! I've been fiddling with a one-to-many ORM relationship for an hour now, but I still don't understand why the following error occurs:
Invalid argument supplied for foreach() (View: C:\xampp\htdocs\lar.ru\app\views\cabinet.blade.php)
public function short(){
return $this->hasOne('Site', 'owner');
}
public function Index(){
if(Auth::check()) {
return View::make('cabinet')->with('sites', Auth::user()->short()->getResults());
}else{
return View::make('cabinet.guest');
}
}
@foreach($sites as $site)
<ul>
<li>url: {{ $site->url }}</li>
<li>title: {{ $site->title }}</li>
<li>description: {{ $site->description }}</li>
<li>keywords: {{ $site->keywords }}</li>
</ul>
@endforeach
return Auth::user()->short()->getResults();
Answer the question
In order to leave comments, you need to log in
Speak One to Many, Write One to One
public function short () {
return $this->hasMany('Site', 'owner', 'login');
}
If using the login and owner columns is not something 100% necessary, I would do so. The text of the scripts is not complete, only the necessary parts.
Mysql:
Users table:
id,login Sites
table:
id, users_id,url,title
Laravel
Models:
Users:
public function sites(){
return $this->hasMany('Site');
}
public funtion user() {
return $this->belongsTo('User');
}
// Используем IOC контейнер, чтобы в будущем было легче тестировать, также строка
// $this->userManager->getSites() гораздо более понятна через 3 месяца, чем
// Auth::user()->short()->getResults()
use Acme\UserManager as UserManager;
protected $userManager;
public function __construct(UserManager $userManager) {
$this->userManager = $userManager;
}
public function index(){
return View::make('cabinet')->with('sites', $this->userManager->getSites());
}
public function getSites() {
if (Auth::check()) {
return User::find( Auth::id() )->sites()->get();
}
return false;
}
@if($sites)
@foreach($sites as $site)
<ul>
<li>url: {{ $site->url }}</li>
<li>title: {{ $site->title }}</li>
<li>description: {{ $site->description }}</li>
<li>keywords: {{ $site->keywords }}</li>
</ul>
@endforeach
@elseif
<p>Войдите, чтобы пользоваться сервисом</p>
@endif
public function sites(){
return $this->hasMany('Site', 'owner', 'login');
}
public funtion user() {
return $this->belongsTo('User' , 'owner', 'login');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question