Your question is just about entries without relationships but your code example is attempting to display both items with a relationship and without a relationship. I think your example is making things a bit more complicated than this needs to be. Rather than looping through both sections (databytes and databyteSeries), I believe you only need to loop through one section. The databyteSeries
section, as you've described it, has a relation field for databytes
, so all the info you need to know about databytes
should be available to you in the relation field.
Let me know if the following example gets at what you are going for. It simplifies your loop to just the databyteSeries
section, and then uses Twig's length filter to test the entry.relatedDatabytes
field to see if it has any entries. If there are related databytes, it displays one output, and if there are not, it displays an alternative output.
I've also updated the method in which you were using to output the first item in the series. Rather than loop through the entire entry.relatedDatabytes
field and just output the first item using a loop.first
conditional, I've updated the code to use entry.relatedDatabytes.first()
. Using the first()
method on an EntryModel will just grab the first item, and then you can output it as you wish with whatever variable you assign it to. Below, I've assigned the first item to the firstInSeries
variable.
{% paginate craft.entries
.section('databyteSeries')
.limit(6)
as entries
%}
{# Loop through databyteSeries entries #}
{% for entry in entries %}
{% if entry.relatedDatabytes|length %}
{# Display the first item in a Databyte Series that has a relationship #}
{% set firstInSeries = entry.relatedDatabytes.first() %}
{{ firstInSeries.title }}
{% else %}
{# Display the Databyte Series name that has no relationships #}
{{ entry.title }}
{% endif %}
{% endfor %}
{% endpaginate %}
UPDATE
Based on your clarification in the comments and your potential solution, here's another method to consider using Craft's without filter:
{# Get all databyteSeries and databytes #}
{% set databyteSeries = craft.entries.section('databyteSeries').limit(null) %}
{% set databytes = craft.entries.section('databytes').limit(null).indexBy('id') %}
{# Determine which databytes already have a relationship to a databyteSeries #}
{% set alreadyUsedDatabytes = craft.entries.section('databytes').relatedTo(databyteSeries).indexBy('id') %}
{# Use the without filter to remove all 'alreadyUsedDatabytes' from the complete 'databytes' result, so you are left with only 'unusedDatabytes' #}
{% set unusedDatabytes = databytes|without(alreadyUsedDatabytes) %}
{# Output the unusedDatabytes #}
<ul>
{% for entry in unusedDatabytes %}
<li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
{% endfor %}
</ul>
I have not tested this code so let me know if you run into any issues to troubleshoot.
databyteSeries
channel) just display the first entry in that series and don't display it from thedatabytes
channel.